puretppc
puretppc

Reputation: 3292

How do I find the amount of items being selected in a ListBox?

I'm trying to find out just how many items are being selected when the user clicks the button.

Here is what I've tried:

private void button1_Click(object sender, EventArgs e)
{
    ListItem li;
    int x = 0;
    foreach ( li in listBox1.Items) 
    {
        if (li.Selected == true)
        {
            x++;
        }
    }
}

But instead it's giving me an error.

Type and identifier are both required in a foreach statement

Also, is there a specific method in Windows Form Application that would count the amount of items in a List Box?

Upvotes: 0

Views: 175

Answers (3)

Damith
Damith

Reputation: 63105

you can use SelectedIndices or SelectedItems to get the count of selected items like below

listBox1.SelectedIndices.Count

Or

listBox1.SelectedIndices.Count

and Items.Count to get amount of items in a List Box

ListBox1.Items.Count

in yourForeach you need to specify the Type, Try below

int x = 0;
foreach(ListItem item in ListBox1.Items)
{
    if (item.Selected) 
       x++;
}

Upvotes: 0

nonexistent myth
nonexistent myth

Reputation: 135

This gives you the list of selected items. Check the count property istBox1.SelectedItems.Count to get the list of items selected.

var selectedItems = listBox1.SelectedItems;

Upvotes: 1

azisfatoni
azisfatoni

Reputation: 95

There is a method in ListBox class to get the amount of selected item:

int numberSelectedItems = listBox1.SelectedItems.Count;

Upvotes: 2

Related Questions