标签:
有时候combox下拉项就是几条固定的,不需要做数据绑定,但是如果直接采用字符串集合编辑器的时候,SelectedValue貌似会不起作用。
于是简单的封装一下
/// <summary> /// 绑定combox 按顺序填写value、member 示例:InitCombox.BindCombox(cbxStatus,"1","启用","0","禁用"); /// </summary> /// <param name="box"></param> /// <param name="valueMember"></param> public static void BindCombox(ComboBox box, params string[] valueMember) { List<ComboxItem> items = new List<ComboxItem>(); for (int i = 0; i < valueMember.Length / 2; i++) { int j = i * 2; items.Add(new ComboxItem { ValueMember = valueMember[j], DisplayMember = valueMember[j + 1] }); } box.DataSource = items; box.DisplayMember = "DisplayMember"; box.ValueMember = "ValueMember"; box.SelectedIndex = -1; } /// <summary> /// 绑定combox 按顺序填写value、member 示例:InitCombox.BindCombox(cbxStatus,0,"1","启用","0","禁用"); /// </summary> /// <param name="box"></param> /// <param name="index"></param> /// <param name="valueMember"></param> public static void BindCombox(ComboBox box, int index, params string[] valueMember) { List<ComboxItem> items = new List<ComboxItem>(); for (int i = 0; i < valueMember.Length / 2; i++) { int j = i * 2; items.Add(new ComboxItem { ValueMember = valueMember[j], DisplayMember = valueMember[j + 1] }); } box.DataSource = items; box.DisplayMember = "DisplayMember"; box.ValueMember = "ValueMember"; box.SelectedIndex = index; }
构造自定义ComboxItem项
public class ComboxItem { public string DisplayMember { get; set; } public string ValueMember { get; set; } }
使用的时候还是蛮方便的
InitCombox.BindCombox(cbxSFKS, 0, "0", "未空驶", "1", "空驶");
标签:
原文地址:http://www.cnblogs.com/njcxwz/p/4602702.html