本文中我將和大家討論關(guān)于在WinForm開發(fā)中給CheckedlistBox空間綁定數(shù)據(jù)源,并獲取控件中選中的所有元素的顯示文本(DisplayMember)和對應(yīng)的實(shí)際值(ValueMember)的問題,后者將是討論的重點(diǎn)。
為了更方便地說明,首先我要預(yù)設(shè)一些條件。
條件預(yù)設(shè):
1、已定義一個(gè)DataTable對象myDataTable,并且myDataTable的字段及數(shù)據(jù)如下:
| ID | 分類名稱(TypeName) |
| 1 | 金屬制品 |
| 2 | 通用及專用機(jī)械設(shè)備 |
| 3 | 紙及紙制品 |
| 4 | 交通運(yùn)輸設(shè)備 |
| 5 | 電氣機(jī)械及器材 |
| 6 | 通信設(shè)備 |
| 7 | 計(jì)算機(jī)及其他 |
| 8 | 電子設(shè)備 |
| 9 | 儀器儀表及文化 |
| 10 | 辦公用機(jī)械 |
2、WinForm狀體中有一個(gè)CheckedlistBox控件,ID為:myCheckedlistBox;一個(gè)文本控件,ID為:DisplayText;兩個(gè)按鈕:獲取已選的文本(ID:GetText),獲取已選的實(shí)際值(ID:GetValue)。如下:
?
具體實(shí)現(xiàn):
1、給CheckedlistBox控件myCheckedlistBox綁定數(shù)據(jù)源,這個(gè)方法很簡單,固定程式,網(wǎng)上一搜一大把,就直接上代碼了
this.myCheckedlistBox.DataSource?=?myDataTable;? ??this.myCheckedlistBox.ValueMember?=?"ID";? ??this.myCheckedlistBox.DisplayMember?=?"TypeName";?? 2、獲取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;? ??}??? 3、獲取CheckedlistBox控件myCheckedlistBox中已選中的所有元素對應(yīng)的實(shí)際值(ValueMember)。
///?<summary>? ??///?按鈕(GetValue)單擊事件:獲取已選的實(shí)際值? ??///?</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;? ??}??? ?
轉(zhuǎn)載于:https://www.cnblogs.com/zhcw/archive/2011/10/12/2208458.html
總結(jié)
以上是生活随笔為你收集整理的WinForm(C#)CheckedlistBox绑定数据,并获得选中的值(ValueMember)和显示文本(DisplayMember...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。