简体   繁体   English

同步。 两个多选列表框的SelectedIndex

[英]Sync. SelectedIndex of two multiselect Listboxes

I'm strungling to sync. 我正在努力同步。 the selectedIndexs of two multi-select Listboxes. 两个多选列表框的selectedIndexs。 With single-select enabled the code is just: 启用单选功能后,代码仅为:

 private void libHT_SelectedIndexChanged(object sender, EventArgs e)
    {
        libMonth.SelectedIndex = libHT.SelectedIndex;
    }

But this doesn't work if multi-select is enabled. 但是,如果启用了多选功能,则无法使用。 Can you help me? 你能帮助我吗? Do I have to use a for or foreach? 我必须使用for或foreach吗?

Thanks for your help. 谢谢你的帮助。 Thomas 汤玛士

There is the SelectedIndices property. SelectedIndices属性。

private void libHT_SelectedIndexChanged(object sender, EventArgs e)
{
        libMonth.SelectedIndices.Clear();
        foreach (var index in libHT.SelectedIndices.Cast<int>())
        {
            libMonth.SelectedIndices.Add(index);
        }
}

Try that 试试看

Yes, you will have to loop over all the selections. 是的,您将不得不遍历所有选择。 Code like below can help you with that 如下代码可以帮助您

private void libHT_SelectedIndexChanged(object sender, EventArgs e) {
    libMonth.SelectedIndices.Clear();
    foreach (int indx in libHT.SelectedIndices)
        libMonth.SelectedIndices.Add(indx);
}

Don't forget: 不要忘记:

  1. To hook the index changed event: libHT.SelectedIndexChanged += libHT_SelectedIndexChanged; 挂钩索引更改事件: libHT.SelectedIndexChanged += libHT_SelectedIndexChanged;
  2. To set the selection mode correctly libHT.SelectionMode = libMonth.SelectionMode = SelectionMode.MultiExtended; 正确设置选择模式libHT.SelectionMode = libMonth.SelectionMode = SelectionMode.MultiExtended;
  3. To watch out for your programmatic selection, causing infinite recursion 要注意您的程序选择,从而导致无限递归

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM