By default, the ComboBox in winform is set to display the list in multiple texts, which is usually not in line with your daily applications,
Because daily applications usually bind key-value pairs.
So what should we do in the form of key-value pairs?
Because the value of each item in combox is an object, it is actually a key/value pair.
I use an instance of the following class as an item:
/// <Summary>
/// ComboBox item
/// </Summary>
Class listitem: system. Object
{
Private string _ value = string. empty;
Private string _ text = string. empty;
/// <Summary>
/// Value
/// </Summary>
Public String Value
{
Get {return this. _ value;} set {This. _ value = value ;}
}
/// <Summary>
/// Displayed text
/// </Summary>
Public String text
{
Get {return this. _ text;} set {This. _ text = value ;}
}
Public listitem (string value, string text)
{
This. _ value = value;
This. _ text = text;
}
Public override string tostring ()
{
Return this. _ text;
}
}
This class defines the value of ComboBox. First, we define a listitem list as the data source of ComboBox:
List <listitem> items = new list <listitem> ();
Items. Add (New listitem ("0", "item_0_text "));
Items. Add (New listitem ("1", "item_shorttext "));
Items. Add (New listitem ("2", "item_2_text "));
Items. Add (New listitem ("3", "item_3_text "));
Items. Add (New listitem ("4", "item_4_text "));
Items. Add (New listitem ("5", "item_5_text "));
Then perform the following settings:
// Maps the data source attributes to the ComboBox attributes.
Drptest. displaymember = "text"; // display
Drptest. valuemember = "value"; // Value
Then you can bind it:
Drptest. datasource = items; // bind data
After binding data, you can set the default selection items and values:
Drptest. selectedvalue = "4"; // set the selection item
// Obtain the selected items
Listitem selecteditem = (listitem) drptest. selecteditem;
String value = selecteditem. value; // Value
String text = selecteditem. Text; // displayed text
For other operations, just draw a gourd.