我的代码中有一个探针。我希望两个列表框之间有相同的选择,但我有stackoverflow错误,我理解我的错误,但我找不到解决方案。有人可以帮帮我吗?
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int i = 0;
while(i<listBox1.Items.Count)
{
listBox2.SetSelected(i, listBox1.GetSelected(i));
i++;
}
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
int i = 0;
while (i < listBox2.Items.Count)
{
listBox1.SetSelected(i, listBox2.GetSelected(i));
i++;
}
}
答案 0 :(得分:1)
您可以在设置所选索引之前删除事件处理程序,然后再次添加事件处理程序。
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int i = 0;
listBox2.SelectedIndexChanged -= listBox2_SelectedIndexChanged;
while (i < listBox1.Items.Count)
{
listBox2.SetSelected(i, listBox1.GetSelected(i));
i++;
}
listBox2.SelectedIndexChanged += listBox2_SelectedIndexChanged;
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
int i = 0;
listBox1.SelectedIndexChanged -= listBox1_SelectedIndexChanged;
while (i < listBox2.Items.Count)
{
listBox1.SetSelected(i, listBox2.GetSelected(i));
i++;
}
listBox1.SelectedIndexChanged += listBox1_SelectedIndexChanged;
}