Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 如何在不使用for循环的情况下从列表框中获取选定项的值_Asp.net_Listbox - Fatal编程技术网

Asp.net 如何在不使用for循环的情况下从列表框中获取选定项的值

Asp.net 如何在不使用for循环的情况下从列表框中获取选定项的值,asp.net,listbox,Asp.net,Listbox,我的aspx页面中有一个列表框,如下所示 <asp:ListBox ID="ddlCategory" runat="server" SelectionMode="Multiple" Width="200" ></asp:ListBox> 我已将其与类别数据集绑定。一切正常。现在我想从服务器端的这个列表框中获取所有选中的项目。实现这些目标有很多方法。但我不想重复每一项。因为列表项有1000个类别 有什么办法可以做到这一点 你可以这样做 var selectedItem

我的aspx页面中有一个列表框,如下所示

<asp:ListBox ID="ddlCategory" runat="server" SelectionMode="Multiple" Width="200"
></asp:ListBox>

我已将其与类别数据集绑定。一切正常。现在我想从服务器端的这个列表框中获取所有选中的项目。实现这些目标有很多方法。但我不想重复每一项。因为列表项有1000个类别


有什么办法可以做到这一点

你可以这样做

var selectedItems = from li in ddlCategory.Items.Cast<ListItem>()
                    where li.Selected == true
                    select li;
var selectedItems=来自ddlcontegory.Items.Cast()中的li
其中li.Selected==true
选择李;
在这里看看实现它的另一种方法


您可以获得所选项目的所有索引:

        int [] indexes= ListBox1.GetSelectedIndices();
        for (int i = 0; i < indexes.Length; i++)
        {
            // ListBox1.Items[i]  ;
        }
int[]index=ListBox1.GetSelectedIndices();
for(int i=0;i
以下是一些示例,它们将对您有所帮助

Dim lst As New System.Web.UI.WebControls.ListBox
lst.Items.Add(New ListItem("1", 1))
lst.Items.Add(New ListItem("2", 2))
lst.Items.Add(New ListItem("3", 3))
lst.SelectionMode = ListSelectionMode.Multiple
lst.Items(0).Selected = True
lst.Items(2).Selected = True
Dim selectedItems As List(Of ListItem) = (From li In lst.Items.Cast(Of ListItem)() Where li.Selected = True Select li).ToList

您选择的任何方式都会遍历集合以检查每个项的状态。否则它怎么知道找到了所有选定的项目?你想要一段代码愚弄你,让你相信它不会迭代吗?可能是这样的:
ddlcogory.Items.Where(item=>item.Selected)这实际上是Linq,不是lambda。。。Lambda看起来像这样,例如:o=>o.Id==1改变了我的措辞,但这并没有停止实现其结果:)我知道,只是想指出它,这样人们就不会误会:)解决方案本身当然是好的+1.