WinForm完成為ComboBox綁定命據源並供給下拉提醒功效。本站提示廣大學習愛好者:(WinForm完成為ComboBox綁定命據源並供給下拉提醒功效)文章只能為提供參考,不一定能成為您想要的結果。以下是WinForm完成為ComboBox綁定命據源並供給下拉提醒功效正文
本文實例展現了WinForm完成為ComboBox綁定命據源並供給下拉提醒功效,這是一個異常有適用價值的功效,詳細完成辦法以下:
重要功效代碼以下:
/// <summary> /// 為ComboBox綁定命據源並供給下拉提醒 /// </summary> /// <typeparam name="T">泛型</typeparam> /// <param name="combox">ComboBox</param> /// <param name="list">數據源</param> /// <param name="displayMember">顯示字段</param> /// <param name="valueMember">隱式字段</param> /// <param name="displayText">下拉提醒文字</param> public static void Bind<T>(this ComboBox combox, IList<T> 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<T>(IList<T> list, string displayMember, string displayText) { Object _obj = Activator.CreateInstance<T>(); Type _type = _obj.GetType(); if (!string.IsNullOrEmpty(displayMember)) { PropertyInfo _displayProperty = _type.GetProperty(displayMember); _displayProperty.SetValue(_obj, displayText, null); } list.Insert(0, (T)_obj); }
應用示例:
List<CommonEntity> Sources = new List<CommonEntity>(); 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); } }
代碼運轉後果以下: