5

I am confused on how to retrieve multi selected values from listbox in wpf.

In XAML I have the following listbox with selection mode multiple.

 <ListBox Height="100" HorizontalAlignment="Left" Margin="139,207,0,0" Name="listBox1" VerticalAlignment="Top" Width="120" SelectionChanged="listBox1_SelectionChanged" SelectionMode="Multiple" />    

 <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="319,220,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />

How do I check in foreach loop now?

        foreach (ListItem li in listBox1.Items)
        {
                ?? // how to check li is selected or not
        }
1

2 Answers 2

10

You will find them in ListBox.SelectedItems.

foreach (var item in listBox1.SelectedItems)
{

}
5
  • 1
    Oh thnx..it was SelectedItems not items.
    – user2118542
    Commented Oct 1, 2013 at 19:05
  • thanks for your answer - is there any way to obtain the classes which each SelectedItem contains?
    – BenKoshy
    Commented Jul 24, 2017 at 5:12
  • 1
    Sorry, I'm not sure what you mean. SelectedItems is a selection of items from your Items or ItemsSource collection and of same type. If you have multiple classes in there you could use typeof or nameof operator to distinguish between them or show their name.
    – LPL
    Commented Jul 24, 2017 at 10:25
  • thx for your response - what i mean: each selected item represents an instance of a Person class (which i've defined in my code). I want to get to that same person instance given a particular selectedItem instance - is there a way to do this?
    – BenKoshy
    Commented Jul 24, 2017 at 11:19
  • 1
    Each SelectedItem is a reference to the corresponding Item instance. Does this answer your question? Maybe it's better to ask this as a new question because it's not related to this question and I'm still unsure what the problem is. Sorry.
    – LPL
    Commented Jul 24, 2017 at 14:16
0

another example

int j = 0;
for (int i = 0; i < lbItems.Items.Count; i++)
{
   if (lbItems.Items[i] == lbItems.SelectedItems[0])
   j++;
}
MessageBox.Show(lbItems.Items.IndexOf(lbItems.SelectedItems[0]).ToString()
+ string.Format("\r\nThere are {0} occurences of this object in this list",j) )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.