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

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.

This question is related to c# asp.net list foreach checkboxlist

The answer is


I like to use this simple method to get the selected values and join them into a string

private string JoinCBLSelectedValues(CheckBoxList cbl, string separator = "")
{
    return string.Join(separator, cbl.Items.Cast<ListItem>().Where(li => li.Selected).ToList());
}

Just in case you want to store the selected values in single column seperated by , then you can use below approach

string selectedItems = String.Join(",", CBLGold.Items.OfType<ListItem>().Where(r => r.Selected).Select(r => r.Value));

if you want to store Text not values then Change the r.Value to r.Text


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.

Every ListControl object has an Items property of type ListItemCollection. ListItemCollection exposes a collection of ListItems, each of which have a Selected property.

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

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

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

string s= string.Empty

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

{

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

}

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

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

If you have a databound checklistbox it does not work to get item(j).Selected, because the control does not have a selected attribute. If you clearSelections i.e. on Load, then apparently it now understands item(j).selected.


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

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

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.

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)

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:

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


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to foreach

Angular ForEach in Angular4/Typescript? How to use forEach in vueJs? Python foreach equivalent Get current index from foreach loop TypeScript for ... of with index / key? JavaScript: Difference between .forEach() and .map() JSON forEach get Key and Value Laravel blade check empty foreach Go to "next" iteration in JavaScript forEach loop Why is "forEach not a function" for this object?

Examples related to checkboxlist

How to get values of selected items in CheckBoxList with foreach in ASP.NET C#? How to loop through a checkboxlist and to find what's checked and not checked?