如何用ASP中的foreach获取CheckBoxList中所选项的值。净c#吗?

时间:2022-10-19 11:18:20

I have a CheckBoxList like this:

我有这样一个清单:

<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从这个复选框列表中获取所选项的值,并将这些值放入一个列表中。

Note: I would prefer the code to be short.

注意:我希望代码简短。

8 个解决方案

#1


164  

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:

如果你只是想要列表。

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

#2


10  

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...

#3


8  

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

#4


1  

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 ListControl object has an Items property of type ListItemCollection. ListItemCollection exposes a collection of ListItems, each of which have a Selected property.

每个ListControl对象都具有ListItemCollection类型的Items属性。ListItemCollection公开了一组listitem,每个都有一个选定的属性。

C Sharp:

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()

#5


1  

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

在@Tim Schmelter上进行充值,以返回列表

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

#6


0  

string s= string.Empty

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

{

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

}

#7


0  

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

#8


0  

This thread was by far the best with many good examples!

这条线是迄今为止最好的,有许多很好的例子!

One thing that i ran in to was neither of the examples worked for me and i spent hours of debugging, i could for all the reasons in the world not understand why i dident managed to get the selected values from my checkbox list. Was it becasue of my master page? Or because i was using a ModalPopup with AjaxControlkit or was I going the right way when creating my checkboxlist from a database query?

我遇到的一件事是,这两个例子对我都不起作用,我花了好几个小时调试,我不明白为什么dident能从我的复选框列表中获得所选值。是因为我的主页吗?或者因为我在使用AjaxControlkit的ModalPopup,或者是因为我在从数据库查询创建复选框列表时走对了方向?

I finally realized that i've missed an important part in all of this...

我终于意识到我错过了这一切的一个重要部分……

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.

在我的codebehind中,我在Page_Load事件中从sql db中创建了一个checkboxlist,在button_click事件中,从checkboxlist中获取所有的get值。

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事件重新创建了复选框列表,因此当它运行我的get复选框值时没有任何复选框被选中……我没有在page_load事件中添加if (!this.IsPostBack)

I hope that my misstake and this answer can help minimize some debugging hours for some out there.

我希望我的错误和这个答案可以帮助减少一些调试时间。

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函数中使用:

    bill@contoso.com; jeff@corp.inc; sam@dot.net

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.

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

#1


164  

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:

如果你只是想要列表。

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

#2


10  

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...

#3


8  

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

#4


1  

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 ListControl object has an Items property of type ListItemCollection. ListItemCollection exposes a collection of ListItems, each of which have a Selected property.

每个ListControl对象都具有ListItemCollection类型的Items属性。ListItemCollection公开了一组listitem,每个都有一个选定的属性。

C Sharp:

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()

#5


1  

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

在@Tim Schmelter上进行充值,以返回列表

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

#6


0  

string s= string.Empty

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

{

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

}

#7


0  

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

#8


0  

This thread was by far the best with many good examples!

这条线是迄今为止最好的,有许多很好的例子!

One thing that i ran in to was neither of the examples worked for me and i spent hours of debugging, i could for all the reasons in the world not understand why i dident managed to get the selected values from my checkbox list. Was it becasue of my master page? Or because i was using a ModalPopup with AjaxControlkit or was I going the right way when creating my checkboxlist from a database query?

我遇到的一件事是,这两个例子对我都不起作用,我花了好几个小时调试,我不明白为什么dident能从我的复选框列表中获得所选值。是因为我的主页吗?或者因为我在使用AjaxControlkit的ModalPopup,或者是因为我在从数据库查询创建复选框列表时走对了方向?

I finally realized that i've missed an important part in all of this...

我终于意识到我错过了这一切的一个重要部分……

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.

在我的codebehind中,我在Page_Load事件中从sql db中创建了一个checkboxlist,在button_click事件中,从checkboxlist中获取所有的get值。

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事件重新创建了复选框列表,因此当它运行我的get复选框值时没有任何复选框被选中……我没有在page_load事件中添加if (!this.IsPostBack)

I hope that my misstake and this answer can help minimize some debugging hours for some out there.

我希望我的错误和这个答案可以帮助减少一些调试时间。

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函数中使用:

    bill@contoso.com; jeff@corp.inc; sam@dot.net

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.

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