0

I have a ListBox containing two items:

Item1 Item2

If I double click on Item1 a message should pop up with the text "Hello!". If I double click Item2 a message should pop up with the text "Bye!".

Whith the code below I'm obviously doing something wrong...

private void ListBox_DoubleClick(object sender, EventArgs e)
{

if (ListBox.SelectedIndex = 1)
{
MessageBox.Show("Hello!");
}

if (ListBox.SelectedIndex = 2)
{
MessageBox.Show("Bye!");
}

} 

2 Answers 2

3

Two things:

  1. Lists and arrays are zero based so you should check for index 0 and

  2. = is an assignment, you should use == in if statements

    private void ListBox_DoubleClick(object sender, EventArgs e)
    {
    
      if (ListBox.SelectedIndex == 0)
      {
         MessageBox.Show("Hello!");
      }
    
      if (ListBox.SelectedIndex == 1)  
      {
        MessageBox.Show("Bye!");
      }
    

    }

Sign up to request clarification or add additional context in comments.

Comments

1

Use a zero based index

private void ListBox_DoubleClick(object sender, EventArgs e)
{

  if (ListBox.SelectedIndex == 0)
  {
    MessageBox.Show("Hello!");
  }

  if (ListBox.SelectedIndex == 1)
  {
    MessageBox.Show("Bye!");
  }  
} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.