如何只检查checklistbox中的一项
我有一个复选框控件,我想一次仅选择一项,我目前正在使用此代码执行相同的操作。
private void CLSTVariable_ItemCheck(object sender, ItemCheckEventArgs e)
{
// Local variable
int ListIndex;
CLSTVariable.ItemCheck -= CLSTVariable_ItemCheck;
for (ListIndex = 0;
ListIndex < CLSTVariable.Items.Count;
ListIndex++)
{
// Unchecked all items that is not currently selected
if (CLSTVariable.SelectedIndex != ListIndex)
{
// set item as unchecked
CLSTVariable.SetItemChecked(ListIndex, false);
} // if
else
{
// set selected item as checked
CLSTVariable.SetItemChecked(ListIndex, true);
}
} // for
CLSTVariable.ItemCheck += CLSTVariable_ItemCheck;
}
这段代码工作正常。
但问题是,当我一次又一次单击所选项目时,不应取消选中该所选项目,这意味着至少应始终检查一个项目...
I have a check list box control and I want to select only one item at a time and I am currently using this code to do the same.
private void CLSTVariable_ItemCheck(object sender, ItemCheckEventArgs e)
{
// Local variable
int ListIndex;
CLSTVariable.ItemCheck -= CLSTVariable_ItemCheck;
for (ListIndex = 0;
ListIndex < CLSTVariable.Items.Count;
ListIndex++)
{
// Unchecked all items that is not currently selected
if (CLSTVariable.SelectedIndex != ListIndex)
{
// set item as unchecked
CLSTVariable.SetItemChecked(ListIndex, false);
} // if
else
{
// set selected item as checked
CLSTVariable.SetItemChecked(ListIndex, true);
}
} // for
CLSTVariable.ItemCheck += CLSTVariable_ItemCheck;
}
this code is working fine.
but problem is that when I click again and again on selected item then that selected item should not be unchecked, means at least one item should be checked always...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我同意上面评论者的观点 - 你应该考虑使用单选按钮。但如果您确实需要 CheckedListBox,请改用此 ItemChecked 事件处理程序:
I agree with commentators above - you should consider using radiobuttons. But if you really need CheckedListBox, then use this ItemChecked event handler instead:
“至少应始终检查一项”
当前的解决方案(最后一项)允许检查项目。如果您的目的是始终选择一个项目,请将其用作 MouseUp 事件,
"at least one item should be checked always"
The current solution (the last one) allows items to be checked off. If your purpose is to select exactly one item at all times, use this as a MouseUp event,
嗯,这是对我的回答!我无法让上面的代码在checkedListBox1_ItemCheck 中工作。我必须修改其中的一部分并将其包含在checkedListBox1_SelectedIndexChanged 事件中。但我无法将原始代码全部删除。这是我添加的内容...
基本上,如果您选中了超过 1 个框,请将最后一个框切换为新框。我很好奇为什么原始代码不起作用。为什么我的新代码必须有它才能工作?谢谢。
Well, it was an answer to me! I couldn't get the above code to work in the checkedListBox1_ItemCheck. I had to modify a portion of it ans include it in the checkedListBox1_SelectedIndexChanged event. But I couldn't remove the original code all together. Here is what I've added...
Which is basically, if you have more than 1 box checked, switch the last one for the new one. I'm curious why the original code didn't work. And why it has to be there for my new code to work? Thank you.
我发现这段代码运行得很好
I found this code it work so well