如何在ASP.NET C#中使用foreach获取CheckBoxList中选定项的值?

我有一个这样的CheckBoxList:


<asp:CheckBoxList ID="CBLGold" runat="server" CssClass="cbl">

    <asp:ListItem Value="TGJU"> TG </asp:ListItem>

    <asp:ListItem Value="GOLDOZ"> Gold </asp:ListItem>

    <asp:ListItem Value="SILVEROZ"> Silver </asp:ListItem>

    <asp:ListItem Value="NERKH"> NE </asp:ListItem>

    <asp:ListItem Value="TALA"> Tala </asp:ListItem>

    <asp:ListItem Value="YARAN"> Sekeh </asp:ListItem>

</asp:CheckBoxList>

现在,我想使用foreach从此CheckBoxList中获取所选项目的值,并将其放入列表中。


注意:我希望代码简短。


胡说叔叔
浏览 649回答 3
3回答

守着星空守着你

&nbsp;foreach (ListItem item in CBLGold.Items)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (item.Selected)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string selectedValue = item.Value;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }

心有法竹

按照这里的建议,我添加了一个扩展方法,以使用LINQ返回继承自的任何类型的所选项目的列表。System.Web.UI.WebControls.ListControl每个ListControl对象都有一个Itemstype属性ListItemCollection。&nbsp; ListItemCollection公开的集合ListItems,每个都有一个Selected属性。C夏普:public static IEnumerable<ListItem> GetSelectedItems(this ListControl checkBoxList){&nbsp; &nbsp; return from ListItem li in checkBoxList.Items where li.Selected select li;}Visual Basic:<Extension()> _Public Function GetSelectedItems(ByVal checkBoxList As ListControl) As IEnumerable(Of ListItem)&nbsp; &nbsp; Return From li As ListItem In checkBoxList.Items Where li.SelectedEnd Function然后,仅使用以下两种语言即可:myCheckBoxList.GetSelectedItems()
打开App,查看更多内容
随时随地看视频慕课网APP