Adrian Romero
Adrian Romero

Reputation: 17

Selecting both listbox item by just selecting on one listbox item from another listbox

First I'm going to select an item from ListBox1 then if I select an item in ListBox1, the corresponding index of ListBox2 should be selected also.

my code for ListBox1

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    listBox1.SelectedIndex = listBox2.SelectedIndex;
}

here's for ListBox2

private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    listBox1.SelectedIndex = listBox2.SelectedIndex;
}

I didn't understand the method clearly and there must be a confusion happening.

I just need help in this part and hope you guys could share some knowledge about this.

Upvotes: 0

Views: 59

Answers (1)

Salah Akbari
Salah Akbari

Reputation: 39946

Change your code like this:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
     if (listBox2.Items.Count >= listBox1.SelectedIndex + 1)
     {
          listBox2.SelectedIndex = listBox1.SelectedIndex;
     }
}

private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    if (listBox1.Items.Count >= listBox2.SelectedIndex + 1)
    {
         listBox1.SelectedIndex = listBox2.SelectedIndex;               
    }
}

Upvotes: 1

Related Questions