[英]Drag a item from Treeview to ListBox on Windows Forms (C#)
[英]Populate files into a listbox from a folder in C# windows forms
我是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");
}
这可能有用;)
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(@"C:\TestLoadFiles");
FileInfo[] Files = dinfo.GetFiles("*.rtdl");
foreach (FileInfo file in Files)
{
listbox2.Items.Add(file.Name);
}
}
我猜想错误的事件。 将该代码移动到窗体/控件的构造函数或将其附加到另一个控件的事件。 当列表框的初始状态为空时,在SelectedIndexChanged上重新填充listBox没有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.