关键代码:
/// <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); } }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }代码效果:
希望有所帮助!
[WinForm]为ComboBox绑定数据源并提供下拉提示
时间: 2024-10-26 22:56:28