轉帖|使用教程|編輯:龔雪|2023-08-25 09:55:04.630|閱讀 113 次
概述:本文將為大家介紹在Winform程序開發過程中的一些復選框控件賦值小技巧,希望能幫助到大家~
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
本人在開發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就沒有問題了。
本文轉載自:
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自: