开发者

How do I determine if multiple items are selected in a ListBox

I think it's obvious what I'm trying to do, but if you don't understand, p开发者_运维问答lease ask.

if (listBox1.SelectedIndex == 1  && 2)
{
    label1.Text = "Sometext";
}


SelectedIndices is what you want if you have enabled multi-select. You can also check the size of the SelectedItems property.

The documentation for ListBox.SelectedIndex states:

For a standard ListBox, you can use this property to determine the index of the item that is selected in the ListBox. If the SelectionMode property of the ListBox is set to either SelectionMode.MultiSimple or SelectionMode.MultiExtended (which indicates a multiple-selection ListBox) and multiple items are selected in the list, this property can return the index to any selected item.

Try this

if( listBox1.SelectedItems.Count > 1 )
{
    // multiple items are selected
}


if (listBox1.SelectedIndices.Count > 1) // I'd use to group all of your multi-selection cases
{
   if (listBox1.SelectedIndices.Contains(1) && listBox1.SelectedIndices.Contains(2))
   {
     label1.Text = "Sometext";
   }
}

Keep in mind that the control is 0 based so if you're trying to select the first two options, you'll want to check for 0 (item 1) and 1 (item 2).

edit: modified to handle the requirement listed in comments. Note, there's probably a better way and there may even be a method for this built in (never used the multi-selection list box). But I built a function to handle so you don't have to do it for every scenario.

The function that does the work:

private bool CasesFunction(ListBox lbItem, List<int> validIndices)
{
     for (int index = 0; index < lbItem.Items.Count; index++)
     {
        if (lbItem.SelectedIndices.Contains(index) && !validIndices.Contains(index))
           return false;
     }
     return true;
}

And how I used it:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
   if (listBox1.SelectedIndices.Count > 1)
      {
         List<int> MyCase = new List<int> { 0, 1 };

         if (CasesFunction(listBox1, MyCase))
         {
            label1.Text = "Sometext";
            return;
         }
         else
            label1.Text = "";

         MyCase = new List<int> { 1, 2 }; // can do other checks

         if (CasesFunction(listBox1, MyCase))
         {
            label1.Text = "Sometext 2";
            return;
         }
         else
            label1.Text = "";
      }
      else
         label1.Text = listBox1.SelectedIndex.ToString();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜