Create a class:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Reflection;usingSystem.ComponentModel;namespacewindowsformsapplication1{ Public classenumdescription { Public Static stringGetenumdesc (Enum e) {FieldInfo enuminfo=E.gettype (). GetField (E.tostring ()); Descriptionattribute[] Enumattributes=(descriptionattribute[]) enuminfo. GetCustomAttributes (typeof(DescriptionAttribute),false); if(Enumattributes.length >0) { returnenumattributes[0]. Description; } returne.tostring (); } }}
Page code:
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;namespacewindowsformsapplication1{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); //Init ();Init1 (); } Public voidInit () {Combobox1.datasource= System.Enum.GetNames (typeof(Enum_type)); } /// <summary> ///Reflection Bonding Enumeration/// </summary> Private voidInit1 () {Array Arrs= System.Enum.GetValues (typeof(Enum_type));//get all values of an enumerationDataTable dt =NewDataTable (); Dt. Columns.Add ("String", Type.GetType ("System.String")); Dt. Columns.Add ("Value",typeof(int)); foreach(varArrinchArrs) { stringStrText =Enumdescription.getenumdesc ((enum_type) arr); DataRow Arow=dt. NewRow (); arow[0] =StrText; arow[1] = (int) arr; Dt. Rows.Add (Arow); } Combobox1.datasource=DT; Combobox1.displaymember="String"; Combobox1.valuemember="Value"; } Private voidButton1_Click (Objectsender, EventArgs e) { //The first method of implementation//enum_type ET = enum_type.tet_1; //Combobox1.selectedindex = combobox1.findstring (et.tostring ()); //string str = comboBox1.SelectedItem.ToString (); //The second way of realization intA =Combobox1.selectedindex; System.Diagnostics.Trace.WriteLine (Combobox1.selecteditem); DataRowView Dr=(DataRowView) (Combobox1.selecteditem); Enum_type AE= (enum_type) (Dr. row[1]); } Public enumEnum_type {[Description ("tet_1")] Tet_1=1, [Description ("tet_2")] Tet_2=2, [Description ("Tet_3")] Tet_3=3, } }}
C # ComboBox Binding enumeration mode