C#: Using ListBoxes
Posted by tech on
January 23, 2009
ListBoxes are those same drop down components that you see in HTML forms. The same control called ComboBox works the same way although the appearance would be that of a 1 liner drop down box. Anyway, adding items to a ListBox object is pretty easy. Just do
1 2 | MyListBox.Items.Add("Item 1"); MyListBox.Items.Add("Item 2"); |
But the code above will only add the labels that will apear within the ListBox. What if you want to have a ListBox that acts the same as a drop down HTML form component with a name and value attribute. You can create your own custom class with Name and Value exposed, place them inside an ArrayList object and pass it on to the ListBox’s DataSource property.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class ListBoxItem { public String Name; public String Value; public ListBoxItem(String name, String value) { Name = name; Value = value; } public override String toString() { return Name; } } ArrayList al = new ArrayList(); al.Add(new ListBoxItem("Item 1", "Value1"); al.Add(new ListBoxItem("Item 2", "Value2"); MyListBox.DataSource = al; |
You can then get the selected name (and/or value) of the ListBox by doing this
1 | ((ListBoxItem) MyListBox.SelectedItem).Name |










