【问题标题】:How do I determine if multiple items are selected in a ListBox如何确定列表框中是否选择了多个项目
【发布时间】:2011-06-17 23:25:30
【问题描述】:

我想我想做什么很明显,但如果你不明白,请问。

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

【问题讨论】:

  • 欢迎来到 Stack Overflow!不幸的是,您在这里尝试做什么并不明显 - 如果所选索引同时为 1 和 2,您想设置一些标签?您能否更详细地描述您要完成的工作?
  • 如果我在 Listbox 中选择多个项目,我想更改 Listbox 的属性。

标签: c# listbox operators


【解决方案1】:

如果您启用了多选,SelectedIndices 就是您想要的。您还可以检查 SelectedItems 属性的大小。

ListBox.SelectedIndex 的文档说明:

对于标准列表框,您可以使用此属性来确定列表框中所选项目的索引。 如果 ListBox 的 SelectionMode 属性设置为 SelectionMode.MultiSimple 或 SelectionMode.MultiExtended(表示多选 ListBox)并且在列表中选择了多个项目,则此属性可以返回任何选定项目的索引。

试试这个

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

【讨论】:

  • 如果你认为我没有读 msdn 你错了,所以不需要复制和粘贴。
  • 考虑到您在问题中几乎没有提供任何信息,当有人试图帮助您利用自己的空闲时间时,请不要那么痛苦。
  • 您究竟在寻找什么答案?他的回复检查是否选择了超过 1 个项目,这就是您所要求的。
  • 哈哈,哇,我不敢相信这个答案似乎冒犯了你。您的示例使用 SelectedIndex 属性的事实使得假设您没有阅读文档是非常合理的。如果你有,那你为什么不这么说或提供一个更好的例子?您是如何错过同一页面下方的 SelectedIndices 的。太棒了。
  • 因为有多个selectxxxxxxxxx,我不知道该选哪一个,顺便说一句,你很粗鲁。
【解决方案2】:
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";
   }
}

请记住,控件是基于 0 的,因此如果您尝试选择前两个选项,则需要检查 0(第 1 项)和 1(第 2 项)。

edit: 修改以处理 cmets 中列出的要求。请注意,可能有更好的方法,甚至可能有一种内置方法(从未使用过多选列表框)。但是我构建了一个函数来处理,所以你不必为每个场景都这样做。

完成工作的函数:

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;
}

以及我是如何使用它的:

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();
}

【讨论】:

  • 我刚刚粘贴了您的代码,它似乎可以工作,但是我已经选择了列表框中的所有项目,它仍然可以工作。 How can I prevent it from working when items that shouldnt be selected are selected?
  • @Liger86 - 定义“作品”和“不应该被选中”。你显然没有告诉我们你想要完成什么。
  • 没关系,帮助我的是你的代码的第三行。
猜你喜欢
  • 2011-07-26
  • 1970-01-01
  • 2014-01-29
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多