No ListItem in Windows Forms
After working in .Net web development for years, I'm not spending some time doing Windows Forms development. Today I ran into something rather surprising.
When adding values to a drop down list in ASP.net webpages, I would typically create a ListItem with the Name/Value pare and add that to the dropdown. Very simple to do. Windows Forms does not seem to have an equivalent for adding to comboboxes (there is a ListItem object, but it is not the same thing). There for if you want to add an item to the combobox that has differing name/values, you need to implement your own ListItem-like class.
Thankfully it's pretty easy to do just that (you can just copy the code below if you like)...
public class ComboBoxItem
{
private string name;
private int value;
public ComboBoxItem(string initialName, int initialValue)
{
this.name = initialName;
this.value = initialValue;
}
public override string ToString()
{
return this.name;
}
}
Now you can add items to your combobox like so:
this.myComboBox.Items.Add(new ComboBoxItem("Item 1", 1));
this.myComboBox.Items.Add(new ComboBoxItem("Item 2", 2));
this.myComboBox.Items.Add(new ComboBoxItem("Item 3", 3));
Notice that this class also includes an override for ToString(), which allows the display on the combobox to be the Name instead of the Value.
I think you may also be able to use the web (ASP.net) version of this object to do this (System.Web.UI.WebControls.ListItem) but something about mixing Web and Windows Forms elements makes me feel dirty.
I should also note that the code above is mostly borrowed from another website but for the life of me, I cannot find that site again to give them the credit they deserve. If you happen to know which/where that site is, please let me know via email or the comments below.
This article has been view 1963 times.
|