How to set multiple selected items on a WinForms ListBox

前端 未结 1 1177
南旧
南旧 2021-01-22 00:40

I have a System.Windows.Forms.ListBox in multiple selection mode and a set of items I\'d like to be selected. How do I do that?

[Test]
public void SetListBox()
         


        
相关标签:
1条回答
  • 2021-01-22 01:16

    Do this:

    selectedItems.Select(sd => listBox.Items.IndexOf(sd)).Where(i => i >= 0).ToList().ForEach(i => listBox.SetSelected(i, true));
    

    For:

        [Test]
        public void SetListBox()
        {
            var listBox = new ListBox();
            var items = new List<string>{"one", "two", "three", "four"};
            listBox.SelectionMode = SelectionMode.MultiSimple;
            listBox.Items.AddRange(items.ToArray());
    
            var selectedItems = new List<string> {"two", "four"};
            selectedItems.Select(sd => listBox.Items.IndexOf(sd)).Where(i => i >= 0).ToList().ForEach(i => listBox.SetSelected(i, true));
    
            Assert.AreEqual(selectedItems, listBox.SelectedItems);
        }
    
    0 讨论(0)
提交回复
热议问题