WinForm(C#)CheckedlistBox綁定數(shù)據(jù),并獲得選中的值(ValueMember)和顯示文本(DisplayMember)
本文中我將和大家討論關(guān)于在WinForm開發(fā)中給CheckedlistBox空間綁定數(shù)據(jù)源彼乌,并獲取控件中選中的所有元素的顯示文本(DisplayMember)和對應(yīng)的實(shí)際值(ValueMember)的問題棺聊,后者將是討論的重點(diǎn)畔况。
為了更方便地說明剩檀,首先我要預(yù)設(shè)一些條件。
一汞扎、條件預(yù)設(shè):
- 已定義一個(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ī)械
-
WinForm狀體中有一個(gè)CheckedlistBox控件,ID為:myCheckedlistBox澈魄;一個(gè)文本控件景鼠,ID為:DisplayText;兩個(gè)按鈕:獲取已選的文本(ID:GetText)痹扇,獲取已選的實(shí)際值(ID:GetValue)铛漓。如下:
1.png
二溯香、具體實(shí)現(xiàn):
- 給CheckedlistBox控件myCheckedlistBox綁定數(shù)據(jù)源,這個(gè)方法很簡單浓恶,固定程式玫坛,
網(wǎng)上一搜一大把,就直接上代碼了
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中已選中的所有元素對應(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;
}
3.png