Reputation: 4845
I am working on a Windows Form right now, specifically, a combo box.
Traditionally, one can use/access/define items or strings into the collection through Visual Studio's GUI in the Properties menu. With that said, I would like to do this programatically.
I have two List<string>
. Let's say the first List
are names, and the second List
are ages.
How does one store the entire first List
into the collection, so I can use the comboBox
to access them?
Upon clicking on an item in this collection, for example, the fifth name, how do I get
the index of this item?
So far, I have created my form, and laid the skeleton of the win forms application, but the part of storing the list into the collection is stopping me from moving forward - thank you.
Upvotes: 2
Views: 3999
Reputation: 2053
You can try:
for (int i = 0; i < list.count; i++)
{
combobox.Items.Add(list[i]);
}
And to get the index you could use:
combobox.selectedindex;
I just typed this straight up so use it as a guide more than a copy + paste job :)
Upvotes: 3
Reputation: 19340
For the list of strings it can be done like this
comboBox.DataSource = myList;
If you don't want to tie your list in Datasource, still one line
comboBox.DataSource = myList.ToArray().Clone();
Now, if this is list of Strings
you can get the whole string
string s = (string)comboBox.SelectedItem; // vs comboBox.SelectedIndex
Upvotes: 2