標籤:winform style c class blog tar
本文中我將和大家討論關於在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;
- }
本文宜城小子 發於:http://blog.yotuo.net(轉載請保留此資訊)
首發地址:http://blog.yotuo.net/post/2010/04/Get_CheckedlistBox_ValueMember_DisplayMember.html