【问题标题】:List Box control in asp.netasp.net中的列表框控件
【发布时间】:2011-02-08 09:47:25
【问题描述】:

我有两个列表框控件 Listbox1 和 Listbox2。我想获取从 C# 中的 Listbox1 中选择的 Listbox2 项目的计数?假设我在 Listbox1 中总共有 7 个项目,而我在 Listbox2 控件中只选择了 3 个项目。我想在 C# 中获取 Listbox2 的项目数?

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    想知道为什么没有人使用 Linq。


    @Riya:我理解您的要求,因为您想要 ListBox2 项目中存在的 ListBox1 中的 SelectedItems 计数。如果是这样,请这样做。

    var filteredListCount = ListBox2.Items
        .Cast<ListItem>()
        .Where(li => 
            ListBox1.Items
                .Cast<ListItem>()
                .Where(item => item.Selected)
                .Select(item => item.Text).Contains(li.Text))
        .Count();
    

    【讨论】:

      【解决方案2】:

      在选择选择时通过选定的项目循环

      类似这样的:

           int count = 0;    
              foreach(string itemListbox2 in listBox2.Items)
              {
                  if (itemListbox2.Selected)
                  {    
                       foreach(string itemListbox1 in listbox1.Items)
                       {
                         if (itemListbox1.Selected)
                         {
                            if(itemListbox1.Equals(itemListbox2))
                            {
                              count++;
                              break;
                            }
                         }
                      }
                  }
              }
      

      【讨论】:

      • asp.net 表单中没有名为 SelectedItems 的属性。它用于winforms。有一半的心思来贬低你。所以请尽快更正:)
      【解决方案3】:

      您可以在 ListBox1 中的所有选定项目上循环,并在循环内搜索 ListBox2 中具有相同值的项目,如果它被选中,则增加一个计数器。

      【讨论】:

        【解决方案4】:

        asp.net 中的列表框没有 SelectedItems。因此循环遍历项目并检查它们是否被选中。如果是这样,请在另一个列表中找到具有相同值的项目。如果您找到相应的项目,请数数。像这样:

        int count = 0;
        foreach (ListItem item in secondListBox.Items)
        {
            if (item.Selected)
            {
                ListItem itemWithSameValue = firstListBox.Items.FindByValue(item.Value);
                if (itemWithSameValue != null)
                {
                    count++;
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多