0
votes

I have 2 Listboxes , each are on different tab page

listBox1 with items A,B,C and listBox2 with exactly same items A,B,C

When I select Item A from listBox1, I want Item A from listBox2 selected aswell and vice versa

I use this code :

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            string item = listBox1.SelectedItem.ToString();
            int index = listBox2_Fichiers.FindString(item);
            listBox2.SetSelected(index, true);
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

            string item = listBox2.SelectedItem.ToString();
            int index = listBox1_Fichiers.FindString(item);
            listBox1.SetSelected(index, true);
}

It works only in one way, from 1 to 2 or from 2 to 1 , but when I try to activate both I get this exception: System.StackOverflowException

What am I missing ?

2
What's happening is probably that you got an endless loop because listBox1_SelectedIndexChanged will call listBox2_SelectedIndexChanged and vice-versa.smoksnes

2 Answers

1
votes

It is because everytime you call SetSelected, SelectedIndexChanged can be called.

This creates an infinite calling of listBox1.SetSelected > listBox1_SelectedIndexChanged > listBox2.SetSelected > listBox2_SelectedIndexChanged > listBox1.SetSelected > ....

Eventually, system stops you by throwing a StackOverflowException.

private bool mirroring = false;

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (mirroring) return;
    mirroring = true;

    string item = listBox1.SelectedItem.ToString();
    int index = listBox2_Fichiers.FindString(item);
    listBox2.SetSelected(index, true);

    mirroring = false;
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
    if (mirroring) return;
    mirroring = true;

    string item = listBox2.SelectedItem.ToString();
    int index = listBox1_Fichiers.FindString(item);
    listBox1.SetSelected(index, true);

    mirroring = false;
}

It is your responsibility to break the call chain. Simplest way is using a boolean switch.

0
votes
System.StackOverflowException 

exception occurs when you are trying to create a loop of operation. You are changing list1 from list2's listBox2_SelectedIndexChanged event so it changes list1's index which fire list1's listBox1_SelectedIndexChanged event which again fire list2's same as before. So this thing creating a loop of selected index change event and System.StackOverflowException exception thrown. You have to change this event handling to prevent this