WinForm应用实战开发指南 - 复选框控件赋值的小技巧分享 📅 2026/8/5 17:23:39 本人在开发WinForm程序中有一些复选框赋值和获取值的小技巧分享讨论一下。PS给大家推荐一个C#开发可以用到的界面组件——DevExpress WinForms它能完美构建流畅、美观且易于使用的应用程序无论是Office风格的界面还是分析处理大批量的业务数据它都能轻松胜任DevExpress新旧版本帮助文档下载可进QQ qun获取169725316应用场景是这样的如果你有一些需要使用复选框来呈现内容的时候如下图所示以上的切除部分的内容是采用在GroupBox中放置多个CheckBox的方式其实这个部分也可以使用Winform控件种的CheckedListBox控件来呈现内容如下所示。不管采用那种控件我们都会涉及到为它赋值的麻烦我这里封装了一个函数可以很简单的给控件 赋值大致代码如下。CheckBoxListUtil.SetCheck(this.groupRemove, info.切除程度);那么取控件的内容代码是如何的呢代码如下info.切除程度 CheckBoxListUtil.GetCheckedItems(this.groupRemove);赋值和取值通过封装函数调用都非常简单也可以重复利用封装方法函数如下所示。public class CheckBoxListUtil { /// summary /// 如果值列表中有的,根据内容勾选GroupBox里面的成员. /// /summary /// param namegroup包含CheckBox控件组的GroupBox控件/param /// param namevalueList逗号分隔的值列表/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 namegroup包含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 namecblItemsCheckedListBox控件/param /// param namevalueList逗号分隔的值列表/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 namecblItemsCheckedListBox控件/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就没有问题了。本文转载自博客园 - 伍华聪