如何允许用户通过“shift”键对CheckedListBox进行多重检查?
假设我有一个带有项目“1”,“2”,“3”,“4”和“5”的CheckedListBox,我想通过选择选择“2”,“3”和“4” “2”然后按住shift并选择“4”。 有没有内置的方法来实现这个CheckedListBox控件? 我发现了一篇关于如何使用SelectedIndexChanged事件来接近这种行为的文章,但是虽然它检查了多个项目,但它并没有将它们显示为已选中。
http://www.windowsdevelop.com/windows-forms-general/multiple-selection-checkbox-53049.shtml
如果有一个我可以使用的替代控制,那么我也会这样做。
可能有一个更简单的替代方法,但您可以使用ListView
,将CheckBoxes
设置为true
,将HeaderStyle
为None
,以及View
to List
。
更正:
本来应该设置View
to Details
。
不支持多项选择,但我通过搜索找到了CheckedItems。
所选项目是指标记的项目,选中的项目是指已检查的项目。
因此使用。 CheckedItems属性而不是.SelectedItems,如果您想要带有选中复选框的项目。
对于多项目,我今天想出了这个:
List listBox2_selectionhistory = new List (); private void checkedListBox2_SelectedIndexChanged(object sender, EventArgs e) { int actualcount = listBox2_selectionhistory.Count; if (actualcount == 1) { if (Control.ModifierKeys == Keys.Shift) { int lastindex = listBox2_selectionhistory[0]; int currentindex = checkedListBox2.SelectedIndex; int upper = Math.Max(lastindex, currentindex) ; int lower = Math.Min(lastindex, currentindex); for (int i = lower; i < upper; i++) { checkedListBox2.SetItemCheckState(i, CheckState.Checked); } } listBox2_selectionhistory.Clear(); listBox2_selectionhistory.Add(checkedListBox2.SelectedIndex); } else { listBox2_selectionhistory.Clear(); listBox2_selectionhistory.Add(checkedListBox2.SelectedIndex); } }
据我所知,checkedlistbox的SelectionMode只能是one或none,这意味着你永远不能让应用程序一次选择多于1个(我也使用这种行为来简化我的checkedlistboxes代码)
看起来CheckedListBox
控件不支持多项选择(请参阅MSDN )。 它支持检查多个复选框,但不支持同时选中(突出显示)多个项目。
我同意另一个答案,即ListView
可能是获得复选框和多选的最佳方式。
它似乎无法设置查看CheckedListBox.SelectionMode属性中的备注部分
如果想要更方便的选择,请遵循adrift的要求。
private System.Windows.Forms.CheckedListBox LBO1; string mySentLst = string.Join(";", LBO1.CheckedItems.Cast());
请按以下步骤操作:
-
选择
CheckOnClick
= true。 -
如果要检索所选项,请改用
GetItemChecked(int index)
方法。