The*_*ing 3 c# directory checkbox text-files
我想在一个应用程序中使用CheckedListBox,其中ListBox中的每个项目都是我的硬盘驱动器上的文件夹的名称,并且为了从这些文件夹中读取和写入文本文件,我希望确保只有一个文件夹可以在CheckedListBox中的任何一个时间选择一个项目(文件夹)
如何通过C#中的代码实现这一目标?
谢谢阅读 :-)
编辑\更新 - 22/10/2010感谢所有花时间回复的人 - 尤其是Adrift,其更新后的代码完美无缺.
我很欣赏一些评论员对我以这种方式使用checkedlistbox的看法,但是我认为这完全符合我的目的,因为我希望毫无疑问地将文本文件从哪里读取和写入.
祝一切顺利.
我同意这样的评论,当只有一个项目被"检查"时,单选按钮将成为常用的UI元素,但是如果你想坚持使用CheckedListBoxUI,你可以尝试这样的事情:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
CheckedListBox.CheckedIndexCollection checkedIndices = checkedListBox1.CheckedIndices;
if (checkedIndices.Count > 0 && checkedIndices[0] != e.Index)
{
checkedListBox1.SetItemChecked(checkedIndices[0], false);
}
}
Run Code Online (Sandbox Code Playgroud)
您还可能需要设置CheckOnClick到true了CheckedListBox.
编辑
更新了您的评论代码,以取消选中未选中的项目.问题是取消选中先前检查的项会导致事件再次触发.我不知道是否有一种标准的方法来处理这个,但在下面的代码中,我在调用之前分离处理程序SetItemCheck,然后重新附加处理程序.它似乎是一种干净的方式来处理这个,它的工作原理.如果我发现有一种推荐的方法来处理这个问题,我会更新我的答案.
HTH
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
CheckedListBox.CheckedIndexCollection checkedIndices = checkedListBox1.CheckedIndices;
if (checkedIndices.Count > 0)
{
if (checkedIndices[0] != e.Index)
{
// the checked item is not the one being clicked, so we need to uncheck it.
// this will cause the ItemCheck event to fire again, so we detach the handler,
// uncheck it, and reattach the handler
checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
checkedListBox1.SetItemChecked(checkedIndices[0], false);
checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}
else
{
// the user is unchecking the currently checked item, so deselect it
checkedListBox1.SetSelected(e.Index, false);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7180 次 |
| 最近记录: |