WinForm(C#)CheckedlistBox绑定数据,并获得选中的值(ValueMember)和显示文本(DisplayMember)
本文中我将和大家讨论关于在WinForm开发中给CheckedlistBox空间绑定数据源,并获取控件中选中的所有元素的显示文本(DisplayMember)和对应的实际值(ValueMember)的问题,后者将是讨论的重点。
为了更方便地说明,首先我要预设一些条件。
一、条件预设:
- 已定义一个DataTable对象myDataTable,并且myDataTable的字段及数据如下:
ID 分类名称(TypeName)
1 金属制品
2 通用及专用机械设备
3 纸及纸制品
4 交通运输设备
5 电气机械及器材
6 通信设备
7 计算机及其他
8 电子设备
9 仪器仪表及文化
10 办公用机械
-
WinForm状体中有一个CheckedlistBox控件,ID为:myCheckedlistBox;一个文本控件,ID为:DisplayText;两个按钮:获取已选的文本(ID:GetText),获取已选的实际值(ID:GetValue)。如下:
1.png
二、具体实现:
- 给CheckedlistBox控件myCheckedlistBox绑定数据源,这个方法很简单,固定程式,
网上一搜一大把,就直接上代码了
1. this.myCheckedlistBox.DataSource = myDataTable;
2. this.myCheckedlistBox.ValueMember = "ID";
3. this.myCheckedlistBox.DisplayMember = "TypeName";
- 获取CheckedlistBox控件myCheckedlistBox中已选中的所有元素的显示文本(DisplayMember)。
/// <summary>
/// 按钮(GetText)单击事件:获取获取已选的文本
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void GetText_Click(object sender, EventArgs e)
{
string checkedText = string.Empty;
for (int i = 0; i < this.myCheckedlistBox.CheckedItems.Count; i++)
{
checkedText += (String.IsNullOrEmpty(checkedText) ? "" : ",")
+ this.myCheckedlistBox.GetItemText(this.myCheckedlistBox.Items[i]);
}
this.DisplayText.Text = checkedText;
}
2.png
- 获取CheckedlistBox控件myCheckedlistBox中已选中的所有元素对应的实际值(ValueMember)。
/// <summary>
/// 按钮(GetValue)单击事件:获取已选的实际值
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void GetValue_Click(object sender, EventArgs e)
{
string checkedText = string.Empty;
for (int i = 0; i < this.myCheckedlistBox.Items.Count; i++)
{
if (this.myCheckedlistBox.GetItemChecked(i))
{
this.myCheckedlistBox.SetSelected(i, true);
checkedText += (String.IsNullOrEmpty(checkedText) ? "" : ",")
+ this.myCheckedlistBox.SelectedValue.ToString();
}
}
this.DisplayText.Text = checkedText;
}
3.png