ComboBoxItem Class for .NET 2.0
2008-06-19
Sometimes when we use the ComboBox control in .NET 2.0, we need add items which have "combination" data, such as we need to add the following data to a ComboBox:
("string1", 1) ("string2", 1) ("string3", 3)
Normally in .NET 2.0, we just add "single" object to a ComboBox control, how we can add above data ?
In .NET 3.0 or above version, there is a new class named "ComboBoxItem", we can use this class to add "complex" data structure objects to a ComboBox. But, in .NET 2.0, we can not have a ComboBoxItem.
OK, just let us make a ComboBoxItem by ourself:
class MyComboBoxItem { public string Name; public int Value;Note: we need override ToString() method, otherwise when we use this ComboBoxItem, you just get the ComboBoxItem name itself.public MyComboBoxItem(string Name, int Value)
public override string ToString() { return this.Name;
} }
Then you can add items like this:
aComboBox.Items.Add(new MyComboBoxItem("string1",1)); aComboBox.Items.Add(new MyComboBoxItem("string2",2)); aComboBox.Items.Add(new MyComboBoxItem("string3",3));And you can get selected value like this:
int selectedValue = ((MyComboBoxItem)aComboBox.SelectedItem).Value;