CheckedListBoxControl 实现复选框的单选与多选功能

时间:2024-04-24 12:38:31

由于工作需要,需要实现复选框的单选与多选功能,找了好多资料都不是很全,经过两天苦苦的挖挖挖,终于完成啦O(∩_∩)O哈哈~

用DEV控件中的CheckedListBoxControl控件,当然VS中的复选框组合控件应该按照下面方法也可以实现该功能,可以试下(⊙o⊙)哦

CheckedListBoxControl 实现复选框的单选与多选功能

代码来啦O(∩_∩)O哈哈~

   //首先触发SelectedIndexChanged事件,然后再触发ItemCheck事件

         //存储选中的复选框的值
string strGXY=string.Empty;
private void chkGXYGrade_SelectedIndexChanged(object sender, EventArgs e)
{ //先把所有的选择框的状态都置为不选中的状态
for (int i = ; i < chkGXYGrade.Items.Count; i++)
{
chkGXYGrade.SetItemCheckState(i, CheckState.Unchecked);
}
} private void chkGXYGrade_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
{
//如果复选框选中的数目大于0,把选中的复选框的索引和e.Index(获取的当前选中点击的复选框的索引)比较,如果相等就把该复选框选中,否则置为非选中状态
if (chkGXYGrade.CheckedItems.Count > )
{
for (int i = ; i < chkGXYGrade.Items.Count; i++)
{
if (i != e.Index)
{
chkGXYGrade.SetItemCheckState(i, CheckState.Unchecked);
}
}
}
else
{ //如果复选框选中的数据小于0 ,则把所有的复选框的状态都置为未选中的状态
for (int i = ; i < chkGXYGrade.Items.Count; i++)
{ chkGXYGrade.SetItemCheckState(i, CheckState.Unchecked);
strGXY = string.Empty;
} } //循环复选框,根据选中的状态来获取选中的复选框的值
for (int i = ; i < chkGXYGrade.Items.Count; i++)
{
if (chkGXYGrade.Items[i].CheckState == CheckState.Checked)
{
strGXY = chkGXYGrade.GetItemText(i).ToString();
}
}
}

级别只能选择一个事件

   //记录复选框选中的状态
CheckState csGXB; //存储复选框选中的值(多选以‘/’区分 )
string strGXB = string.Empty; //先触发SelectedIndexChanged事件,再触发ItemCheck事件
private void chbGXBlb_SelectedIndexChanged(object sender, EventArgs e)
{
switch (csGXB)
{
case CheckState.Checked: strGXB = string.Empty;
for (int i = ; i < chbGXBlb.Items.Count; i++)
{
//获取选中的复选框的值
if (chbGXBlb.GetItemChecked(i))
{
if (strGXB == string.Empty)
{
strGXB = chbGXBlb.GetItemText(i);
}
else
{
strGXB += "/" + chbGXBlb.GetItemText(i);
}
}
}
break;
case CheckState.Unchecked:
strGXB = string.Empty;
for (int i = ; i < chbGXBlb.Items.Count; i++)
{
if (chbGXBlb.GetItemChecked(i))
{
if (strGXB == string.Empty)
{
strGXB = chbGXBlb.GetItemText(i);
}
else
{
strGXB = strGXB + "/" + chbGXBlb.GetItemText(i);
}
}
}
break; } } private void chbGXBlb_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
{
// e.State,获取当前复选框的选中还是未选中的状态(Checked 或UnChecked)
csGXB = e.State;
chbGXBlb_SelectedIndexChanged(null, null);
}

多选:根据选择改变获取值