csharper
csharper

Reputation: 1393

listbox; number of selected items

While using listbox in c#, how can learn the count of selecteditems?

Listbox items: A,B,C,D. For example, I select C and D.

I want to make a loop in order to assign selecteditems.

How can I achieve it? How can I learn the number of selected item?

Thank you

Upvotes: 7

Views: 26399

Answers (4)

Gobind Gupta
Gobind Gupta

Reputation: 223

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

Upvotes: 0

Esam
Esam

Reputation: 31

Use the following code:

This return integer:

 listBox.SelectedItems.Count

this will return the number as string :

listBox.SelectedItems.Count.ToString()

Upvotes: 3

V4Vendetta
V4Vendetta

Reputation: 38230

Maybe you are looking for this listbox1.GetSelectedIndices().Count();

Upvotes: 13

Grant Thomas
Grant Thomas

Reputation: 45068

You ought to be able to achieve this using something like so:

var count = (from item in listBox.Items where item.Selected select item).Count();

The above is a way to get this using Linq (so you will need a reference to System.Linq) but could easily be expanded to use a more primitive means such as a loop.

Upvotes: 0

Related Questions