81

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Amin AmiriDarban
  • 2,031
  • 4
  • 24
  • 32
  • http://stackoverflow.com/questions/9523263/how-can-i-get-the-checkboxlist-selected-values-what-i-have-doesnt-seem-to-work – dotalchemy Sep 20 '13 at 19:13

11 Answers11

209

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:

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();
TylerH
  • 20,799
  • 66
  • 75
  • 101
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • @نرخیاب: edited my answer to show how to select only the values. `var` is just a shortcut for `List`. – Tim Schmelter Sep 20 '13 at 19:19
  • 1
    If you get an error that .Cast is not a method on the ListItemCollection, you'll need to add a reference: "using System.Linq;" – Peter Jacoby Aug 11 '15 at 14:49
  • 1
    Thats exactly what I needed plus to access on server side. String.Join(";", selectedValues.ToArray()) – Muneeb Mirza Jan 05 '16 at 08:31
  • To top up on this solution, to convert the values to list of int, just do this ".Cast().Where(li => li.Selected).Select(li => li.Value).Select(int.Parse).ToList()" – TPG Dec 11 '17 at 06:31
15
foreach (ListItem item in CBLGold.Items)
{
    if (item.Selected)
    {
        string selectedValue = item.Value;
    }
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Arif Ansari
  • 472
  • 1
  • 4
  • 12
11

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...
mreyeros
  • 4,359
  • 20
  • 24
2

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()
KyleMit
  • 30,350
  • 66
  • 462
  • 664
1
List<string> values =new list<string>();
foreach(ListItem Item in ChkList.Item)
{
    if(Item.Selected)
    values.Add(item.Value);
}
1

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();
TPG
  • 2,811
  • 1
  • 31
  • 52
1

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.

Jared Forth
  • 1,577
  • 6
  • 17
  • 32
1

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

student
  • 321
  • 2
  • 10
0
string s= string.Empty

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

{

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

}
Sarvesh Mishra
  • 2,014
  • 15
  • 30
  • 3
    1. You should explain your code a little. 2. Why are you posting an answer to a one year old question that already has an accepted answer? – fancyPants Dec 27 '14 at 13:15
0

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:

    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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Slint
  • 355
  • 1
  • 4
  • 17
  • This does not provide an answer to the question; it's just a longwinded description of how you wrote a similar thing but it didn't work because you... didn't write it correctly. Answers on Stack Overflow should be direct attempts to answer *the question that was asked* or *problem that was posed*; they're not the place to share similar anecdotes. – TylerH Feb 19 '20 at 21:12
0

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());
}
Matthew Lock
  • 13,144
  • 12
  • 92
  • 130