加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

将文件填充到C#windows窗体中的文件夹的列表框中

发布时间:2020-12-15 06:19:50 所属栏目:百科 来源:网络整理
导读:我是C#的新手,我有2个列表框l – istBox1和listBox2,我想将文件夹中的文件加载到这些列表框中. 我试过这样的: listBox1中: private void listBox1_SelectedIndexChanged(object sender,EventArgs e) { DirectoryInfo dinfo = new DirectoryInfo(@"C:TestL
我是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,"*.other");
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读