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

后端 未结 12 1053
失恋的感觉
失恋的感觉 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:55

    In my case i had 10k+ items, the basic loop method was taking almost a minute to complete. Using @DiogoNeves answer and extending it i wanted to be able to select all (Ctrl+A) & copy (Ctrl+C). i handled this 2 ways. i used the BeginUpdate() and EndUpdate() to defer drawing but i also added a direct copy all (Ctrl+Shift+C) which doesn't even bother to select the items before copying.

    private static void HandleListBoxKeyEvents(object sender, KeyEventArgs e)
    {
        var lb = sender as ListBox;
        // if copy
        if (e.Control && e.KeyCode == Keys.C)
        {
            // if shift is also down, copy everything!
            var itemstocopy = e.Shift ? lb.Items.Cast() : lb.SelectedItems.Cast();
            // build clipboard buffer
            var copy_buffer = new StringBuilder();
            foreach (object item in itemstocopy)
                copy_buffer.AppendLine(item?.ToString());
            if (copy_buffer.Length > 0)
                Clipboard.SetText(copy_buffer.ToString());
        }
        // if select all
        else if (e.Control && e.KeyCode == Keys.A)
        {
            lb.BeginUpdate();
            for (var i = 0; i < lb.Items.Count; i++)
                lb.SetSelected(i, true);
            lb.EndUpdate();
        }
    }
    
        

    提交回复
    热议问题