C#如何使用MultiSimple as SelectionMode同步两个Lisbox

C#如何使用MultiSimple as SelectionMode同步两个Lisbox,c#,listbox,selecteditem,selectedindex,C#,Listbox,Selecteditem,Selectedindex,正如问题所示,我有两个列表框。我使用一个从数据库中获取ID,另一个向用户显示相关信息 我已经在其他表格中使用了此选项,如: int IDIndex = Listbox1.SelectedIndex; ListBox2.SelectedIndex = IDIndex; 如果ListBox1选择了多个项目,我该怎么做 @编辑:下面的代码是我用于此的代码。同时检查@Pikoh的答案 Boolean IndexChanged = false; int IDIndex = -1; foreach(int

正如问题所示,我有两个列表框。我使用一个从数据库中获取ID,另一个向用户显示相关信息

我已经在其他表格中使用了此选项,如:

int IDIndex = Listbox1.SelectedIndex;
ListBox2.SelectedIndex = IDIndex;
如果ListBox1选择了多个项目,我该怎么做

@编辑:下面的代码是我用于此的代码。同时检查@Pikoh的答案

Boolean IndexChanged = false;
int IDIndex = -1;
foreach(int ind in ListBox1.SelectedIndices)
{
    if (!ListBox2.SelectedIndices.Contains(ind)) {
        ListBox2.SetSelected(ind, true);
        //Index Selected: ind
        IDIndex = ind;
        IndexChanged = true;
    }
}
if (!IndexChanged)
{
    foreach (int ind in ListBox2.SelectedIndices)
    {
        if (!ListBox1.SelectedIndices.Contains(ind))
        {
            ListBox2.SetSelected(ind, false);
            //Index Deselected: ind
            IDIndex = ind;
            IndexChanged = true;
        }
    }
}

这使我能够知道更改了哪个索引。我的程序必须知道这一点才能检查数据库中的相关信息。

您可以使用
selectedDices
集合。然后,您可以执行以下操作:

if (Listbox1.SelectedIndices.Count>0)
{
     IDIndex = Listbox1.SelectedIndices[0];
}


是winforms吗?是的,通过可视化研究,我想要的行为是,如果用户选择[0],系统将在第二个列表框中选择[0]。如果用户选择[2],则也会选择[2]。如果用户取消选择[2],则只会选择[0]。等等我应该使用循环吗?我已经在上面插入了我的代码(我将要使用的代码)
IDIndex = this.listBox1.SelectedIndices.Cast<int>().First();
Listbox2.ClearSelected();
foreach (int ind in Listbox1.SelectedIndices)
{
     Listbox2.SetSelected(ind, true);
}