Reproduced in: http://blog.csdn.net/fcsh820/article/details/3867053
Thanks to the original author for sharing such a good article.
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
//////////////////////////////////////// //////////////////////////////////////// ////////////
Based on the original article. I thought of this method:
Private void loadcomboxyear ()
{
List <keyvaluepair <string, int> listitem = new list <keyvaluepair <string, int> ();
Listitem. Add (New keyvaluepair <string, int> ("2011", 2011 ));
Listitem. Add (New keyvaluepair <string, int> ("2012", 2012 ));
Combobox3.datasource = listitem;
Combobox3.displaymember = "key ";
Combobox3.valuemember = "value ";
Combobox3.selectedindex = 0;
}
Data Retrieval:
Private void button#click (Object sender, eventargs E)
{
Keyvaluepair <string, int> keyValue = (keyvaluepair <string, int>) combobox3.selecteditem;
MessageBox. Show ("key:" + keyValue. Key + ", value:" + keyValue. value );
}