本文中我将和你们讨论关于在WinForm开发中给CheckedlistBox空间绑定数据源,并获取控件中选中的全部元素的显示文本(DisplayMember)和对应的实际值(ValueMember)的问题,后者将是讨论的重点。html
为了更方便地说明,首先我要预设一些条件。post
条件预设:this
一、已定义一个DataTable对象myDataTable,而且myDataTable的字段及数据以下:spa
ID 分类名称(TypeName) 1 金属制品 2 通用及专用机械设备 3 纸及纸制品 4 交通运输设备 5 电气机械及器材 6 通讯设备 7 计算机及其余 8 电子设备 9 仪器仪表及文化 10 办公用机械 二、WinForm状体中有一个CheckedlistBox控件,ID为:myCheckedlistBox;一个文本控件,ID为:DisplayText;两个按钮:获取已选的文本(ID:GetText),获取已选的实际值(ID:GetValue)。以下:.net
具体实现:orm
一、给CheckedlistBox控件myCheckedlistBox绑定数据源,这个方法很简单,固定程式,网上一搜一大把,就直接上代码了htm
- this.myCheckedlistBox.DataSource = myDataTable;
- this.myCheckedlistBox.ValueMember = "ID";
- 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;
- }
三、获取CheckedlistBox控件myCheckedlistBox中已选中的全部元素对应的实际值(ValueMember)。blog
- /// <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;
- }
本文做者:宜城小子 发于:http://blog.yotuo.net(转载请保留此信息)
首发地址:http://blog.yotuo.net/post/2010/04/Get_CheckedlistBox_ValueMember_DisplayMember.html事件