Reputation: 3
I am brand new to C# and I am doing a simple task: returning a list of logical drives to my comboBox represented on my Windows form. I simply created a comboBox added the following code compiled and executed. I had expected to see a list of logical drives to show up in my drop down. This is the code that I used.
ComboBox cb = new ComboBox();
string[] drives = Environment.GetLogicalDrives();
foreach (string drive in drives)
{
cb.Items.add(drive);
}
Upvotes: 0
Views: 322
Reputation: 3207
Using properties window, give a name to your ComboBox. It might be already called comboBox1.
Now, you can refer to it in the code as the name you specified, whether it is cb or comboBox1. Also, you need to use proper capitalization - the method you want is called Add, not add
private void Form1_Load(object sender, EventArgs e)
{
string[] drives = Environment.GetLogicalDrives();
foreach (string drive in drives)
{
comboBox1.Items.Add(drive);
}
}
In your current approach, you have created a new ComboBox, which is different than the one that you placed on your form. As soon as the function stops executing, that ComboBox is destroyed, because it was never placed in the form.
Upvotes: 1
Reputation: 5138
You need to actually add the combo box to the form for it to display like this:
this.Controls.Add(cb);
Or alternatively you could add it using the designer and then just reference the existing combo box to populate the items.
Upvotes: 1