本人在開發WinForm程序中,有一些複選框賦值和獲取值的小技巧,分享討論一下。
PS:給大家推薦一個C#開發可以用到的界面組件——DevExpress WinForms,它能完美構建流暢、美觀且易於使用的應用程序,無論是Office風格的界面,還是分析處理大批量的業務數據,它都能輕鬆勝任!
DevExpress技術交流羣8:523159565 歡迎一起進羣討論
應用場景是這樣的,如果你有一些需要使用複選框來呈現內容的時候,如下圖所示:
以上的切除部分的內容,是採用在GroupBox中放置多個CheckBox的方式;其實這個部分也可以使用Winform控件種的CheckedListBox控件來呈現內容,如下所示。
不管採用那種控件,我們都會涉及到爲它賦值的麻煩,我這裏封裝了一個函數,可以很簡單的給控件 賦值,大致代碼如下。
CheckBoxListUtil.SetCheck(this.groupRemove, info.切除程度);
那麼取控件的內容代碼是如何的呢,代碼如下:
info.切除程度 = CheckBoxListUtil.GetCheckedItems(this.groupRemove);
賦值和取值通過封裝函數調用,都非常簡單,也可以重複利用,封裝方法函數如下所示。
public class CheckBoxListUtil { /// <summary> /// 如果值列表中有的,根據內容勾選GroupBox裏面的成員. /// </summary> /// <param name="group">包含CheckBox控件組的GroupBox控件</param> /// <param name="valueList">逗號分隔的值列表</param> public static void SetCheck(GroupBox group, string valueList) { string[] strtemp = valueList.Split(','); foreach (string str in strtemp) { foreach (Control control in group.Controls) { CheckBox chk = control as CheckBox; if (chk != null && chk.Text == str) { chk.Checked = true; } } } } /// <summary> /// 獲取GroupBox控件成員勾選的值 /// </summary> /// <param name="group">包含CheckBox控件組的GroupBox控件</param> /// <returns>返回逗號分隔的值列表</returns> public static string GetCheckedItems(GroupBox group) { string resultList = ""; foreach (Control control in group.Controls) { CheckBox chk = control as CheckBox; if (chk != null && chk.Checked) { resultList += string.Format("{0},", chk.Text); } } return resultList.Trim(','); } /// <summary> /// 如果值列表中有的,根據內容勾選CheckedListBox的成員. /// </summary> /// <param name="cblItems">CheckedListBox控件</param> /// <param name="valueList">逗號分隔的值列表</param> public static void SetCheck(CheckedListBox cblItems, string valueList) { string[] strtemp = valueList.Split(','); foreach (string str in strtemp) { for (int i = 0; i < cblItems.Items.Count; i++) { if (cblItems.GetItemText(cblItems.Items[i]) == str) { cblItems.SetItemChecked(i, true); } } } } /// <summary> /// 獲取CheckedListBox控件成員勾選的值 /// </summary> /// <param name="cblItems">CheckedListBox控件</param> /// <returns>返回逗號分隔的值列表</returns> public static string GetCheckedItems(CheckedListBox cblItems) { string resultList = ""; for (int i = 0; i < cblItems.CheckedItems.Count; i++) { if (cblItems.GetItemChecked(i)) { resultList += string.Format("{0},", cblItems.GetItemText(cblItems.Items[i])); } } return resultList.Trim(','); } }
以上代碼分爲兩部分, 其一是對GroupBox的控件組進行操作,第二是對CheckedListBox控件進行操作。
這樣在做複選框的時候,就比較方便一點,如我採用第一種GroupBox控件組方式,根據內容勾選的界面如下所示。
應用上面的輔助類函數,如果你是採用GroupBox方案,你就可以隨便拖幾個CheckBox控件進去就可以了,也犯不着給他取個有意義的名字,因爲不管它是張三還是李四,只要它的父親是GroupBox就沒有問題了。
本文轉載自:博客園 - 伍華聰