本文实例展示了WinForm实现为ComboBox绑定数据源并提供下拉提示功能,这是一个非常有实用价值的功能,具体实现方法如下:
主要功能代码如下:
////// 为ComboBox绑定数据源并提供下拉提示 /// ///泛型 /// ComboBox /// 数据源 /// 显示字段 /// 隐式字段 /// 下拉提示文字 public static void Bind(this ComboBox combox, IList list, string displayMember, string valueMember, string displayText) { AddItem(list, displayMember, displayText); combox.DataSource = list; combox.DisplayMember = displayMember; if (!string.IsNullOrEmpty(valueMember)) combox.ValueMember = valueMember; } private static void AddItem (IList list, string displayMember, string displayText) { Object _obj = Activator.CreateInstance (); Type _type = _obj.GetType(); if (!string.IsNullOrEmpty(displayMember)) { PropertyInfo _displayProperty = _type.GetProperty(displayMember); _displayProperty.SetValue(_obj, displayText, null); } list.Insert(0, (T)_obj); }
使用示例:
ListSources = new List (); private void WinComboBoxToolV2Test_Load(object sender, EventArgs e) { CreateBindSource(5); comboBox1.Bind(Sources, "Name", "Age", "--请选择--"); } private void CreateBindSource(int count) { for (int i = 0; i < count; i++) { CommonEntity _entity = new CommonEntity(); _entity.Age = i; _entity.Name = string.Format("Yan{0}", i); Sources.Add(_entity); } }
代码运行效果如下:



