簡體   English   中英

將文件填充到C#windows窗體中的文件夾的列表框中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM