WinForm应用实战开发指南 - 复选框控件赋值的小技巧分享

本人在开发WinForm程序中,有一些复选框赋值和获取值的小技巧,分享讨论一下。

PS:给大家推荐一个C#开发可以用到的界面组件——DevExpress WinForms,它能完美构建流畅、美观且易于使用的应用程序,无论是Office风格的界面,还是分析处理大批量的业务数据,它都能轻松胜任!

点击获取DevExpress v23.1正式版(Q技术交流:523159565)

应用场景是这样的,如果你有一些需要使用复选框来呈现内容的时候,如下图所示:

WinForm应用实战开发指南 - 复选框控件赋值的小技巧分享

以上的切除部分的内容,是采用在GroupBox中放置多个CheckBox的方式;其实这个部分也可以使用Winform控件种的CheckedListBox控件来呈现内容,如下所示。

WinForm应用实战开发指南 - 复选框控件赋值的小技巧分享

不管采用那种控件,我们都会涉及到为它赋值的麻烦,我这里封装了一个函数,可以很简单的给控件 赋值,大致代码如下。

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控件组方式,根据内容勾选的界面如下所示。

WinForm应用实战开发指南 - 复选框控件赋值的小技巧分享

应用上面的辅助类函数,如果你是采用GroupBox方案,你就可以随便拖几个CheckBox控件进去就可以了,也犯不着给他取个有意义的名字,因为不管它是张三还是李四,只要它的父亲是GroupBox就没有问题了。

本文转载自:博客园 - 伍华聪

猜你喜欢

转载自blog.csdn.net/AABBbaby/article/details/132555675