入门级: WinForm 下的 ComboBox,ListBox 的使用 (二) 数据绑定
有了 上一篇 文章的基础,这样就比较简单了:
先定义一个这样的List:
/// <summary>
///
/// </summary>
public class ListItems : List<ListItem> {
public void Bind(ComboBox control) {
control.DisplayMember = "Text";
control.ValueMember = "Value";
control.DataSource = this;
}
public void Bind(ListBox control) {
control.DisplayMember = "Text";
control.ValueMember = "Value";
control.DataSource = this;
}
public void Bind(DataGridViewComboBoxCell control) {
control.DisplayMember = "Text";
control.ValueMember = "Value";
control.DataSource = this;
}
}
///
/// </summary>
public class ListItems : List<ListItem> {
public void Bind(ComboBox control) {
control.DisplayMember = "Text";
control.ValueMember = "Value";
control.DataSource = this;
}
public void Bind(ListBox control) {
control.DisplayMember = "Text";
control.ValueMember = "Value";
control.DataSource = this;
}
public void Bind(DataGridViewComboBoxCell control) {
control.DisplayMember = "Text";
control.ValueMember = "Value";
control.DataSource = this;
}
}
调用 :
ListItems items = new ListItems();
items.Add(new ListItem(1, "深圳"));
items.Add(new ListItem(2, "北京"));
items.Add(new ListItem(3, "上海"));
ComboBox comboBox = new ComboBox();
items.Bind(comboBox);
this.Controls.Add(comboBox);
items.Add(new ListItem(1, "深圳"));
items.Add(new ListItem(2, "北京"));
items.Add(new ListItem(3, "上海"));
ComboBox comboBox = new ComboBox();
items.Bind(comboBox);
this.Controls.Add(comboBox);