我是 C# 的新手,我有 2 个列表框 l-->istBox1 和 listBox2,我想将文件夹中的文件加载到这些列表框中。
我试过这样的:
listBox1:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(@"C:\TestLoadFiles");
FileInfo[] Files = dinfo.GetFiles("*.rtdl");
foreach (FileInfo file in Files)
{
listbox1.Items.Add(file.Name);
}
}
listBox2:
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(@"C:\TestLoadFiles");
FileInfo[] Files = dinfo.GetFiles("*.dlz");
foreach (FileInfo file in Files)
{
listbox2.Items.Add(file.Name);
}
}
当我运行表单时,文件夹中的文件没有显示???
最佳答案
代替 listBox1_SelectedIndexChanged,更新列表框以防止某些按钮单击,否则您的代码看起来不错。最初您的列表框中可能没有任何项目,这就是为什么当您单击它时 SelectedIndexChanged 不会被触发。
编辑:(由于问题已被编辑,我将更新我的答案)
要用文件填充您的列表框,您应该这样做,在 SelectedIndexChanged 以外的某些事件中。因为在您的应用程序开始时,您的列表框是空的,并且当列表框中有项目并且用户单击它时会触发 SelectedIndexChanged 事件。您可以创建以下功能
private void PopulateListBox(ListBox lsb, string Folder, string FileType)
{
DirectoryInfo dinfo = new DirectoryInfo(Folder);
FileInfo[] Files = dinfo.GetFiles(FileType);
foreach (FileInfo file in Files)
{
lsb.Items.Add(file.Name);
}
}
现在您可以在某些事件中针对按钮单击或表单加载使用您的列表框调用此函数。例如
private void Form1_Load(object sender, EventArgs e)
{
PopulateListBox(listbox1, @"C:\TestLoadFiles", "*.rtld");
PopulateListBox(listbox2, @"C:\TestLoadFiles", "*.other");
}
关于c# - 将文件从 C# Windows 窗体中的文件夹填充到列表框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10516167/