为什么在列表框的智能感知中没有被选中的项目?

本文关键字:项目 感知 列表 智能 为什么 | 更新日期: 2023-09-27 18:17:47

我错过了什么吗?我在ListBox控件上找不到SelectedItems属性。我尝试遍历其中选定的项。是的,属性SelectionMode被设置为多个,这并不重要。

为什么我不能"看到"属性?

为什么在列表框的智能感知中没有被选中的项目?

重要提示:我误以为这是一个Windows窗体问题。对于System.Web.UI.WebControls.ListBox为true。这是关于Windows窗体ListBox

它确实存在,但被标记为

[BrowsableAttribute(false)]

所以智能感知不会显示给你,但你可以使用它。


一个合适的解决方案,也适用于ASP。. NET System.Web.UI.WebControls.ListBox将是:

var selectedItems = from item in myListBox.Items.OfType<ListItem>()
                    where item.Selected;

感谢Noah1989指出SelectedItems属性在WebForms中是而不是。要解决这个问题,只需遍历列表框中的所有项,并询问它们是否被选中:

ListItemCollection collection = new ListItemCollection();
            foreach (ListItem item in ListBox1.Items)
            {
                if (item.Selected)
                    collection.Add(item);
            }

或者像Noah说的那样,直接使用LINQ: from item in items where item.IsSelected