Malasorte
Malasorte

Reputation: 1173

C# - On double click on listbox item

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!");
}

} 

Upvotes: 0

Views: 1251

Answers (2)

David Pilkington
David Pilkington

Reputation: 13620

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!");
  }  
} 

Upvotes: 1

ema
ema

Reputation: 5773

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!");
      }
    

    }

Upvotes: 3

Related Questions