从 ASP 列表框中获取所有选定的值 [英] Getting all selected values from an ASP ListBox

查看:21
本文介绍了从 ASP 列表框中获取所有选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ASP ListBox,它的 SelectionMode 设置为Multiple".有没有办法检索所有选定的元素而不仅仅是最后一个?

I have an ASP ListBox that has the SelectionMode set to "Multiple". Is there any way of retreiving ALL selected elements and not just the last one?

<asp:ListBox ID="lstCart" runat="server" Height="135px" Width="267px" SelectionMode="Multiple"></asp:ListBox>

使用 lstCart.SelectedIndex 只返回最后一个元素(如预期).有什么东西可以让我全部选中吗?

Using lstCart.SelectedIndex just returns the last element (as expected). Is there something that will give me all selected?

推荐答案

您可以使用 ListBox.GetSelectedIndices 方法 并遍历结果,然后通过 items 集合访问每个结果.或者,您可以遍历所有项目并检查它们的 所选属性.

You can use the ListBox.GetSelectedIndices method and loop over the results, then access each one via the items collection. Alternately, you can loop through all the items and check their Selected property.

// GetSelectedIndices
foreach (int i in ListBox1.GetSelectedIndices())
{
    // ListBox1.Items[i] ...
}

// Items collection
foreach (ListItem item in ListBox1.Items)
{
    if (item.Selected)
    {
        // item ...
    }
}

// LINQ over Items collection (must cast Items)
var query = from ListItem item in ListBox1.Items where item.Selected select item;
foreach (ListItem item in query)
{
    // item ...
}

// LINQ lambda syntax
var query = ListBox1.Items.Cast<ListItem>().Where(item => item.Selected);

这篇关于从 ASP 列表框中获取所有选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆