How do I select all items in a listbox on checkbox checked?

后端 未结 12 1071
失恋的感觉
失恋的感觉 2020-12-17 08:31

I need to select all items in a ListBox when a CheckBox is clicked. Is it possible to select all items in the ListBox using a single line of code? Or will I have to loop thr

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-17 08:56

    I have seen a number of (similar) answers all which does logically the same thing, and I was baffled why yet they all dont work for me. The key is setting listbox's SelectionMode to SelectionMode.MultiSimple. It doesn't work with SelectionMode.MultiExtended. Considering to select multiple items in a listbox, you will have selection mode set to multiple mode, and mostly people go for the conventional MultiExtended style, this answer should help a lot. And ya not a foreach, but for.

    You should actually do this:

    lb.SelectionMode = SelectionMode.MultiSimple;
    for (int i = 0; i < lb.Items.Count; i++)
        lb.SetSelected(i, true);
    lb.SelectionMode = //back to what you want
    

    OR

    lb.SelectionMode = SelectionMode.MultiSimple;
    for (int i = 0; i < lb.Items.Count; i++)
        lb.SelectedIndices.Add(i);
    lb.SelectionMode = //back to what you want
    

提交回复
热议问题