Reputation: 1
I have two listbox controls Listbox1 and Listbox2. I want to get the count of items of Listbox2 which are selected from Listbox1 in c#? Suppose i have total 7 items in Listbox1 and from those i have selected only 3 items in Listbox2 control. I want to get the count of items of Listbox2 in C#?
Upvotes: 0
Views: 1208
Reputation: 55200
Wonder why nobody used Linq.
@Riya: I understand your requirement as, you want the Count of SelectedItems in ListBox1 that are present in ListBox2 Items. If so do this.
var filteredListCount = ListBox2.Items
.Cast<ListItem>()
.Where(li =>
ListBox1.Items
.Cast<ListItem>()
.Where(item => item.Selected)
.Select(item => item.Text).Contains(li.Text))
.Count();
Upvotes: 2
Reputation: 2961
Loop thru the selected items when the selection is changed
Something like this:
int count = 0;
foreach(string itemListbox2 in listBox2.Items)
{
if (itemListbox2.Selected)
{
foreach(string itemListbox1 in listbox1.Items)
{
if (itemListbox1.Selected)
{
if(itemListbox1.Equals(itemListbox2))
{
count++;
break;
}
}
}
}
}
Upvotes: 1
Reputation: 1676
A Listbox in asp.net doesn't have SelectedItems. Therefor loop through the Items and check if they are selected. If so, find an item in the other list with the same value. If you find a corresponding item, count it. Like this:
int count = 0;
foreach (ListItem item in secondListBox.Items)
{
if (item.Selected)
{
ListItem itemWithSameValue = firstListBox.Items.FindByValue(item.Value);
if (itemWithSameValue != null)
{
count++;
}
}
}
Upvotes: 0
Reputation: 44595
You can loop on all selected items in ListBox1 and inside the loop you search for an item with the same value in ListBox2 and if it's selected you increment a counter.
Upvotes: 0