2

I'm trying to use C# to select an item in a listbox using a switch statement but nothing happens:

This is my current code:

XAML

<ListBox x:Name="test" (XAML OMITED) SelectionChanged="test_SelectionChanged">
 <ListBoxItem Content="name 1" />

c#

 private void test_SelectionChanged(object sender,  System.EventArgs e)
    {
        switch (test.SelectedItem.ToString())
        {
            case "name 1":
                MessageBox.Show("X");
                break;
            case "name 2":
                MessageBox.Show("X");
                break;
            default:

                break;
        }

thanks

1
  • 2
    which line do you think is selecting the listbox item in this code? Commented Jul 22, 2013 at 14:07

2 Answers 2

1

The listbox is the sender object so you can access it like so. You just need to cast the sender as a listbox, then your selected item is a listbox item so you would cast it and then you can access the content values. Also when I created my selectionchanged event handler it accepts SelectionChangedEventArgs e not System.EventArgs e, SelectionChangedEventArgs is found in the System.Windows.Controls Namespace, which should already be imported into your class through using statement.

var mySender = (ListBox)sender;
swtich(((ListBoxItem)mySender.SelectedItem).Content.ToString()){

  case "name 1":
            MessageBox.Show("X");
            break;
  case "name 2":
            MessageBox.Show("X");
            break;
  default:
            break;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but I want to call a method in some cases or update a variable?
I saw that after I posted the no need what you could do is switch on the messagebox value I am outputting I will edit for your needs.
0
 private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            foreach (var selectedItem in e.AddedItems)
            {
                switch ((selectedItem as ListBoxItem).Content.ToString())
                {
                    case "name 1":
                        MessageBox.Show("X");
                        break;
                    case "name 2":
                        MessageBox.Show("y");
                        break;
                    default:

                        break;
                }
            }
        }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.