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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18924147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:37:14  来源:igfitidea点击:

How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

c#asp.netlistforeachcheckboxlist

提问by Amin AmiriDarban

I have a CheckBoxList like this:

我有一个这样的 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>

Now I want to get the value of the selected items from this CheckBoxList using foreach, and put the values into a list.

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

采纳答案by Tim Schmelter

Note that I prefer the code to be short.

请注意,我更喜欢简短的代码。

List<ListItem> selected = CBLGold.Items.Cast<ListItem>()
    .Where(li => li.Selected)
    .ToList();

or with a simple foreach:

或者用一个简单的foreach

List<ListItem> selected = new List<ListItem>();
foreach (ListItem item in CBLGold.Items)
    if (item.Selected) selected.Add(item);

If you just want the ListItem.Value:

如果您只想要ListItem.Value

List<string> selectedValues = CBLGold.Items.Cast<ListItem>()
   .Where(li => li.Selected)
   .Select(li => li.Value)
   .ToList();

回答by mreyeros

Good afternoon, you could always use a little LINQ to get the selected list items and then do what you want with the results:

下午好,您总是可以使用一点 LINQ 来获取选定的列表项,然后对结果执行您想要的操作:

var selected = CBLGold.Items.Cast<ListItem>().Where(x => x.Selected);
// work with selected...

回答by Arif Ansari

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

回答by KyleMit

Following suit from the suggestions here, I added an extension method to return a list of the selected items using LINQ for any type that Inherits from System.Web.UI.WebControls.ListControl.

遵循此处的建议,我添加了一个扩展方法,以使用 LINQ 为从.System.Web.UI.WebControls.ListControl

Every ListControlobject has an Itemsproperty of type ListItemCollection. ListItemCollectionexposes a collection of ListItems, each of which have a Selectedproperty.

每个ListControl对象都有一个Items类型的属性ListItemCollectionListItemCollection公开 的集合ListItems,每个集合都有一个Selected属性。

C Sharp:

C锐:

public static IEnumerable<ListItem> GetSelectedItems(this ListControl checkBoxList)
{
    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)
    Return From li As ListItem In checkBoxList.Items Where li.Selected
End Function

Then, just use like this in either language:

然后,在任何一种语言中都这样使用:

myCheckBoxList.GetSelectedItems()

回答by Gopal Reddy Vinnamala

string s= string.Empty

for (int i = 0; i < Chkboxlist.Items.Count; i++)

{

    if (Chkboxlist.Items[i].Selected)
    {
        s+= Chkboxlist.Items[i].Value + ";"; 
    }

}

回答by Rohini Yejju

List<string> values =new list<string>();
foreach(ListItem Item in ChkList.Item)
{
    if(Item.Selected)
    values.Add(item.Value);
}

回答by Slint

In my codebehind i created a checkboxlist from sql db in my Page_Load event and in my button_click event did all the get values from checkboxlist etc.

在我的代码隐藏中,我从 Page_Load 事件中的 sql db 创建了一个复选框列表,并在我的 button_click 事件中从复选框列表等中获取了所有值。

So when i checked some checkboxes and then clicked my button the first thing that happend was that my page_load event recreated the checkboxlist thus not having any boxes checked when it ran my get checkbox values... I've missed to add in the page_load event the if (!this.IsPostBack)

因此,当我检查一些复选框然后单击我的按钮时,发生的第一件事是我的 page_load 事件重新创建了复选框列表,因此在运行我的获取复选框值时没有选中任何框......我错过了添加 page_load 事件if (!this.IsPostBack)

protected void Page_Load(object sender, EventArgs e)
{
   if (!this.IsPostBack)
   {
      // db query and create checkboxlist and other
      SqlConnection dbConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
      string query;
      try
      {
        query = "SELECT [name], [mail] FROM [users]";
        dbConn.Open();
        SqlDataAdapter da = new SqlDataAdapter(query, dbConn);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count != 0)
        {
          checkboxlist1.DataSource = ds;
          checkboxlist1.DataTextField = "name";
          checkboxlist1.DataValueField = "mail";
          checkboxlist1.DataBind();
        }
        else
        {
          Response.Write("No Results found");
        }
       }
       catch (Exception ex)
       {
          Response.Write("<br>" + ex);
       }
       finally
       {
          dbConn.Close();
       }
   }
}

protected void btnSend_Click(object sender, EventArgs e)
 {
   string strChkBox = string.Empty;
   foreach (ListItem li in checkboxlist1.Value)
    {
      if (li.Selected == true)
       {
         strChkBox += li.Value + "; ";    
         // use only   strChkBox += li + ", ";   if you want the name of each checkbox checked rather then it's value.
       }
    }
   Response.Write(strChkBox);
 }

And the output was as expected, a semicolon separeted list for me to use in a mailsend function:

输出符合预期,分号分隔列表供我在 mailsend 函数中使用:

    [email protected]; [email protected]; [email protected]

A long answer to a small problem. Please note that i'm far from an expert at this and know that there are better solutions then this but it might help out for some.

一个小问题的长答案。请注意,我远不是这方面的专家,并且知道有比这更好的解决方案,但它可能对某些人有所帮助。

回答by teapeng

To top up on @Tim Schmelter, in which to get back the List<int>instead,

为@Tim Schmelter 充值,在其中取回List<int>

List<string> selectedValues = CBLGold.Items.Cast<ListItem>()
   .Where(li => li.Selected)
   .Select(li => li.Value)
   .Select(int.Parse)
   .ToList();