WinForm The ComboBox By default is to set the display list in multiple lines, which is usually not in line with everyone's daily application,
Because everyone's daily application is usually the form of key/value pairs to bind it.
Referring to some examples on the web, a helper class was finally written to facilitate the operation of the ComboBox:
Use an instance of the following class as an addition to the ComboBox:
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Windows.Forms;namespacetp7309. winform{ Public classListItem { Public stringKey {Get;Set; } Public stringValue {Get;Set; } PublicListItem (stringStrkey,stringstrvalue) { This. Key =strkey; This. Value =strvalue; } Public Override stringToString () {return This. Key; } /// <summary> ///finds a specific listitem based on value in ListItem (only valid if the ComboBox item is ListItem)/// </summary> /// <param name= "CMB" >combobox to look for</param> /// <param name= "strvalue" >to find the value of ListItem</param> /// <returns>returns the first listitem that meets the criteria in the incoming ComboBox and returns null if none is found.</returns> Public StaticListItem Findbyvalue (ComboBox CMB,stringstrvalue) { foreach(ListItem LiinchCMB. Items) {if(Li. Value = =strvalue) { returnLi; } } return NULL; } /// <summary> ///find a specific listitem based on key in ListItem (only valid if the ComboBox item is ListItem)/// </summary> /// <param name= "CMB" >combobox to look for</param> /// <param name= "strvalue" >to find the key for ListItem</param> /// <returns>returns the first listitem that meets the criteria in the incoming ComboBox and returns null if none is found.</returns> Public StaticListItem Findbytext (ComboBox CMB,stringStrText) { foreach(ListItem LiinchCMB. Items) {if(Li. Value = =StrText) { returnLi; } } return NULL; } }}
Introduce namespaces before use: tp7309. Winform
Add Item:
Cmb1. Items.Add (New ListItem ("Key1", "value1"));
Cmb1. Items.Add (New ListItem ("Key2", "value2"));
Gets the selected item:
ListItem li = (ListItem) cmb1. SelectedItem;
ListItem li1 = Listitem.findbyvalue (CMB1, "value1"); Get the selected item based on key
ListItem Li2 = Listitem.findbytext (CMB1, "Key1"); Gets the selected item based on value
String strkey = li. Key; Get the selected key
string strvalue = li. Value; Gets the selected item value
Set Selected items:
Cmb1. SelectedIndex = 0; Modify selected items according to index
Cmb1. SelectedItem = Listitem.findbyvalue (CMB1, "value1"); Get the selected item based on key
Cmb1. SelectedItem = Listitem.findbytext (CMB1, "Key1"); Gets the selected item based on value