本人在开发Winform程序中,有一个给复选框赋值和获取值的小技巧,分享讨论一下。
PS:给大家推荐一个C#开发可以用到的界面组件——DevExpress WinForms,它能完美构建流畅、美观且易于使用的应用程序,无论是Office风格的界面,还是分析处理大批量的业务数据,它都能轻松胜任!
DevExpress Universal Subscription官方最新版免费下载试用,历史版本下载,在线文档和帮助文件下载-慧都网
应用场景是这样的,如果你有一些需要使用复选框来呈现内容的时候,如下面两图所示:
以上的切除部分的内容,是采用在GroupBox中放置多个CheckBox的方式;其实这个部分也可以使用Winform控件种的CheckedListBox控件来呈现内容。如下所示。
不管采用那种控件,我们都会涉及到为它赋值的麻烦,我这里封装了一个函数,可以很简单的给控件 赋值,大致代码如下。
CheckBoxListUtil.SetCheck(this.groupRemove, info.切除程度);
那么取控件的内容代码是如何的呢,代码如下:
info.切除程度 = CheckBoxListUtil.GetCheckedItems(this.groupRemove);
赋值和取值通过封装函数调用,都非常简单,也可以重复利用,封装方法函数如下所示。
public class CheckBoxListUtil
{
///
/// 如果值列表中有的,根据内容勾选GroupBox里面的成员.
///
/// 包含CheckBox控件组的GroupBox控件
/// 逗号分隔的值列表
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;
}
}
}
}
///
/// 获取GroupBox控件成员勾选的值
///
/// 包含CheckBox控件组的GroupBox控件
/// 返回逗号分隔的值列表
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(',');
}
///
/// 如果值列表中有的,根据内容勾选CheckedListBox的成员.
///
/// CheckedListBox控件
/// 逗号分隔的值列表
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);
}
}
}
}
///
/// 获取CheckedListBox控件成员勾选的值
///
/// CheckedListBox控件
/// 返回逗号分隔的值列表
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就没有问题了。
本文转载自:博客园 - 伍华聪
页面更新:2024-03-25
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号