-1

I have a listbox with content (the numbers 1-2-3-4-5-6) How can I use a selected number in an if-statement?

Now I have something like that:

if (Listbox1.SelectedItem.ToString()=6)
{
...
}

The XAML for my listbox is:

<ListBox x:Name="lb_getallen" 
         HorizontalAlignment = "Center" 
         Height = "124" 
         Margin = "428,28,54,0" 
         VerticalAlignment = "Top" 
         Width = "35" 
         HorizontalContentAlignment = "Center"> 

         <ListBoxItem Content = "1"/> 
         <ListBoxItem Content="2"/> 
         <ListBoxItem Content="3"/> 
         <ListBoxItem Content="4"/> 
         <ListBoxItem Content="5"/> 
         <ListBoxItem Content="6"/> 
</ListBox>
Manuel Zelenka
  • 1,616
  • 2
  • 12
  • 26
  • Do you mean, instead of selected item, you want to use any other item? – Ian Jan 03 '16 at 02:40
  • Take a look at the examples of `.SelectedValue` in [this question](https://stackoverflow.com/questions/4902039/difference-between-selecteditem-selectedvalue-and-selectedvaluepath) for a way to use the actual value of a listbox. – LinkBerest Jan 03 '16 at 03:08
  • @FiliepVerpoucke how do you populate your `ListBox`? Update your question with relevant XAML/code. – dkozl Jan 03 '16 at 10:31
  • Possible duplicate of [LIstbox Selected Item content to textblock](http://stackoverflow.com/questions/7887829/listbox-selected-item-content-to-textblock) – Manuel Zelenka Jan 03 '16 at 16:59

1 Answers1

1

If you added the numbers as ints you can use this:

if (Listbox1.SelectedItem == 6)
{
    // do something
}

Otherwise this would work too:

if (Listbox1.SelectedItem.ToString() == "6")
{
    // do something
}

Note that a comparison is done by ==. A single = is used for assignment.

ToString() returns a string, so you cannot compare it to an int like 6, but to "6".

René Vogt
  • 43,056
  • 14
  • 77
  • 99