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