开发中需要根据下拉框的选择处理一些业务逻辑,使用ID值或Text值都不利于代码维护,所以可以写个扩展方法绑定到枚举上。
public static class Extensions { /// <summary> /// 绑定ComboBoxEx数据源到枚举类型 /// </summary> /// <param name="cmb"></param> /// <param name="enumType"></param> /// <param name="selectIndex"></param> public static void BindToEnumName(this ComboBox cmb, Type enumType, int selectIndex = 0) { cmb.DataSource = Enum.GetNames(enumType); } /// <summary> /// 获取选择项 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cmb"></param> /// <returns></returns> public static T GetSelectedItemToEnum<T>(this ComboBox cmb) { return (T)Enum.Parse(typeof(T), cmb.SelectedItem.ToString(), false); } /// <summary> /// 设置选定项 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cmb"></param> /// <param name="t"></param> public static void SetSelectedItemToEnum<T>(this ComboBox cmb, T t) { cmb.SelectedItem = t.ToString(); } }
调用方法:
private void button1_Click(object sender, EventArgs e) { this.comboBox1.BindToEnumName(typeof(TypeEnum)); } private void button2_Click(object sender, EventArgs e) { var type = this.comboBox1.GetSelectedItemToEnum<TypeEnum>(); this.textBox1.Text = type.ToString() + ":" + (int)type; } private void button3_Click(object sender, EventArgs e) { this.comboBox1.SetSelectedItemToEnum(this.textBox2.Text); } private void button4_Click(object sender, EventArgs e) { this.comboBox1.SetSelectedItemToEnum<TypeEnum>((TypeEnum)(int.Parse(this.textBox3.Text))); } public enum TypeEnum { 类型1 = 1, 类型2 = 2 }