Reputation: 323
I have created a checkedListbox in C# using visual studio. I want to populate the checkedListbox with .txt files located on my hard drive. I found a way to do that following the post below.However, when I run my program, the checkedListbox is empty. Any idea why that's happening?
How to list text files in the selected directory in a listbox?
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\John\Desktop\Test1\Test1\Test1\Data");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
checkedListBox1.Items.Add(file.Name);
}
}
Upvotes: 0
Views: 168
Reputation: 27019
Your code should work but you need to make one small change. Right now you have the code within checkedListBox1_SelectedIndexChanged
but initially there is nothing in your CheckedListBox
so the SelectedIndexChanged
event will not be triggered and thus your code will not be executed; consequently, nothing will show in your CheckedListBox
. Even if you had an item in there, why would you want to do this every time the user checks/unchecks one of the items.
Either double click your form and put that code within Xxx_Load
(where Xxx is the name of the form) event handler or put the code within the constructor after InitializeComponent
.
Or put the code anywhere else where it makes sense.
Upvotes: 2