ListBox select all items

2019-01-26 03:07发布

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 through all items and set selected to true for each one of them?

Thanks :)

10条回答
男人必须洒脱
2楼-- · 2019-01-26 03:53
private void Button_Click(object sender, RoutedEventArgs e)
    {

            listbox.SelectAll();

    }
查看更多
Ridiculous、
3楼-- · 2019-01-26 03:59

Select All is definetly available out of the box:

$("#ListBoxID option").prop("selected", true);
查看更多
不美不萌又怎样
4楼-- · 2019-01-26 04:00

I know this question is tagged with .NET 2.0 but if you have LINQ available to you in 3.5+, you can do the following:

ASP.NET WebForms

var selected = listBox.Items.Cast<System.Web.UI.WebControls.ListItem>().All(i => i.Selected = true);

WinForms

var selected = listBox.SelectedItems.Cast<int>().ToArray();
查看更多
The star\"
5楼-- · 2019-01-26 04:03

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
查看更多
登录 后发表回答