Loop through Visual Studio checkbox list c#

Its a bit easier using Javascript, but here is how to use c# and loop through the variables in a checkbox list control from Visual Studio.

You have a Checkbox List control on your page: CheckBoxList1. You  loop through the list of items and use the data…

In your codebehind, you are in a function to gather the data from objects:

myFunction(){...
// doing stuff
// need to get the data from the check box list checked items
string selectedItems = "";

for(int i = 0; i < CheckBoxList1.Items.Count; i++)
   {
      if (CheckBoxList1.Items[i].Selected)
                {
                  selectedItems += CheckBoxList1.Items[i].Value + ", ";
                 }
    }


...}

If the checkbox list had selected values of SUN, WED and FRI then the string selectedItems would contain the text : “SUN, WED, FRI, ”

I would use  a trim to remove the trailing comma.

 

Here is another method that casts the Checkbox items as a list and uses for each to loop through.

string FoundScholAppSport = "";
 foreach (ListItem val in CheckBoxListSports.Items)
 {
      if (val.Selected)
      {
          FoundScholAppSport += val.Value + " ";
      }
 }

Leave a Reply