简体   繁体   English

asp.net中的列表框控件

[英]List Box control in asp.net

I have two listbox controls Listbox1 and Listbox2. 我有两个列表框控件Listbox1和Listbox2。 I want to get the count of items of Listbox2 which are selected from Listbox1 in c#? 我想获取在C#中从Listbox1中选择的Listbox2的项目数吗? Suppose i have total 7 items in Listbox1 and from those i have selected only 3 items in Listbox2 control. 假设我在Listbox1中总共有7个项目,而我在Listbox2控件中仅选择了3个项目。 I want to get the count of items of Listbox2 in C#? 我想获取C#中Listbox2的项数吗?

Wonder why nobody used Linq. 想知道为什么没人使用Linq。


@Riya: I understand your requirement as, you want the Count of SelectedItems in ListBox1 that are present in ListBox2 Items . @Riya:我了解您的要求,因为您希望对ListBox2 Items中存在的ListBox1中的SelectedItems进行计数 If so do this. 如果是这样,请执行此操作。

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

Loop thru the selected items when the selection is changed 更改选择时,遍历所选项目

Something like this: 像这样:

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

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

A Listbox in asp.net doesn't have SelectedItems. asp.net中的列表框没有SelectedItems。 Therefor loop through the Items and check if they are selected. 因此在项目之间循环并检查是否已选择它们。 If so, find an item in the other list with the same value. 如果是这样,请在另一个列表中找到具有相同值的项目。 If you find a corresponding item, count it. 如果找到相应的项目,则将其计数。 Like this: 像这样:

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

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

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