简体   繁体   English

按当前目录从ComboBox到ListBox筛选文件

[英]Filter files by current directory from ComboBox to a ListBox

I have a combobox that lists directories and I have a listbox that shows files in the directory that is currently selected in the combobox. 我有一个列出目录的组合框,并且有一个列表框显示当前在组合框中选择的目录中的文件。 I want it so when you change the selected item in the combobox, the listbox updates with the new files. 我想要它,因此当您更改组合框中的所选项目时,列表框将使用新文件进行更新。

How do I achieve this? 我该如何实现?

My current attempt: 我目前的尝试:

private void Form1_Load(object sender, EventArgs e)
{
    DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\guest\Desktop\test");
    DirectoryInfo[] folders = dinfo.GetDirectories();
    FileInfo[] Files = dinfo.GetFiles();

    cbobox.DataSource = folders;

    foreach(FileInfo file in Files)
    {
        lstbox.Items.Add(file.Name);
    }
}

You can set dinfo to the path in the combobox . 您可以设置dinfo在路径combobox

Assuming your combo box just has the string of the directory 假设您的组合框只有目录的字符串

dinfo = new DirectoryInfo(combobox.SelectedItem);

and the rest of your code stays the same 而其余的代码保持不变

private void Form1_Load(object sender, EventArgs e)
{
    DirectoryInfo dinfo = new DirectoryInfo(combobox.SelectedItem);
    DirectoryInfo[] folders = dinfo.GetDirectories();
    FileInfo[] Files = dinfo.GetFiles();

    cbobox.DataSource = folders;

    foreach(FileInfo file in Files)
    {
        lstbox.Items.Add(file.Name);
    }
}

If you wanted to change it when a new item in the combobox is selected, you'd need to use an event. 如果要在选择组合框中的新项目时更改它,则需要使用一个事件。

private void Form1_Load(object sender, EventArgs e)
{
    RefreshList();
    combobox.SelectedIndexChanged += 
        new System.EventHandler(ComboBox1_SelectedIndexChanged);
}

private void RefreshList() 
{
    DirectoryInfo dinfo = new DirectoryInfo(combobox.SelectedItem);
    DirectoryInfo[] folders = dinfo.GetDirectories();
    FileInfo[] Files = dinfo.GetFiles();

    cbobox.DataSource = folders;

    foreach(FileInfo file in Files)
    {
        lstbox.Items.Add(file.Name);
    }
}

private void ComboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    RefreshList();
}

Please read 请阅读

This code is assuming your combo box has the name combobox , and the strings in the combo box are the full path (or relative path) to the directory you want to filter by. 此代码假定您的组合框具有名称combobox ,并且组合框中的字符串是您要作为过滤依据的目录的完整路径(或相对路径)。 If it's not you'll need to adapt to serve your purpose. 如果不是,则需要适应以实现您的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM