Saving a user's CheckBoxList selection and re-populating the CheckBoxList from saved data

4.31 (55 votes)

The user has gone to the trouble of selecting a list of checkboxes to indicate their choices. Now you need to re-present their selections so that they can edit them. How do you make sure the correct checkboxes are ticked?

There are two main ways to save CheckBoxList selections in a database. One is to create a new row for each value, and the other is to save the entire selection in one field as a comma-separated string. Which approach you use will depend on whether you want to do further analysis on the selections at a later stage, for example, finding out how many people selected option 2. Saving each value to a separate row makes this process very easy, whereas trying to analyse individual values in a series of comma separated strings is going to really test your string manipulation, and array skills.

Whichever way you choose, you need to first iterate over the ListItem collection of the CheckBoxList to identify which Items have been selected. If you are saving to new rows for each value, you need to ExecuteNonQuery() within the loop. If you are saving one comma separated string, you can use the StringBuilder object to build the string and insert the string after the loop has built the value to be inserted.

ExecuteNonQuery()

[C#]
CheckBoxList chkbx = (CheckBoxList)FormView1.FindControl("CheckBoxList1");
//Set up connection and command objects
//Open connection
for (int i = 0; i < chkbx.Items.Count; i++)
{
if (chkbx.Items[i].Selected)
  {
  cmd.Parameters.AddWithValue("@CategoryID", chkbx.Items[i].Value);
  cmd.ExecuteNonQuery();
  cmd.Parameters.Clear();
  }
}
[VB]
Dim i As Integer
Dim chkbx As CheckBoxList
chkbx = CType(FormView1.FindControl("CheckBoxList1"), CheckBoxList)
For i = 0 To chkbx.Items.Count - 1
  If chkbx.Items(i).Selected Then
    cmd.Parameters.AddWithValue("@CategoryID", chkbx.Items(i).Value);
    cmd.ExecuteNonQuery();
    cmd.Parameters.Clear();
  End If
Next

StringBuilder

[c#]
CheckBoxList chkbx = (CheckBoxList)FormView1.FindControl("CheckBoxList1");
StringBuilder sb = new StringBuilder
//Set up connection and command objects
//Open connection
for (int i = 0; i < chkbx.Items.Count; i++)
{
if (chkbx.Items[i].Selected)
  {
  sb.Append(chkbx.Items[i].Value + ",");
  }
}
string InputString
//Remove last comma from sb
InputString = sb.ToString().SubString(0,sb.ToString().Length()-1);
[VB]
Dim i As Integer
Dim chkbx As CheckBoxList
chkbx = CType(FormView1.FindControl("CheckBoxList1"), CheckBoxList)
Dim sb As StringBuilder = New StringBuilder()
For i = 0 To chkbx.Items.Count - 1
  If chkbx.Items(i).Selected Then
    sb.Append(chkbx.Items(i).Value & ",")
  End If
Next
'Create the value to be inserted by removing the last comma in sb
Dim InputValue As String
InputValue = Left(sb.ToString(), Len(sb.ToString()) - 1)
'Open connection and ExecuteScalar()

ExecuteReader()

Now that the values have been saved, they can easily be extracted and matched up to the CheckBoxList control that appears in the editing page. If the values have been saved to separate rows in the database, unless there is a good reason to bring them back in a DataSet, they will be brought back using a DataReader. The following examples assume this is the case, and during the the Read() method, each value is examined and an attempt to match the value with an existing ListItem in the CheckBoxList is made using FindByValue(). If a match is found, that ListItem's Selected property is set to True.

[C#]
CheckBoxList chkbx = (CheckBoxList)FormView1.FindControl("CheckBoxList1");
while (rdr.Read())
{
  ListItem currentCheckBox = chkbx.Items.FindByValue(rdr["ID"].ToString());
  if (currentCheckBox != null)
  {
    currentCheckBox.Selected = true;
  }
}
[VB]
Dim chkbx As CheckBoxList
chkbx = CType(FormView1.FindControl("CheckBoxList1"), CheckBoxList)
Do While rdr.Read()
  Dim currentCheckBox As ListItem
  currentCheckBox = chkbx.Items.FindByValue(rdr("ID").ToString())
  If currentCheckBox IsNot Nothing Then
    currentCheckBox.Selected = True
  End If
Loop

And that just leaves how to handle the values if they are returned as a comma separated string. Once the value containing the comma-separated string has been extracted form the DataTable/DataReader (as required), the String.Split() method is used to change the string into a one-dimensional array. From that point, matching the individual values to CheckBoxList ListItem objects is the same as before:

[C#]
string[] items = returned_value_from_db.Split(',');
for(int i = 0; i <= items.GetUpperBound(0); i++)
{
ListItem currentCheckBox = chkbx.Items.FindByValue(items["i"].ToString());
  if (currentCheckBox != null)
  {
    currentCheckBox.Selected = true;
  }
}
[VB]
Dim items As String() = sb.ToString().Split(",")
For i = 0 To items.GetUpperBound(0)
  Dim currentCheckBox As ListItem
  currentCheckBox = CheckBoxList2.Items.FindByValue(items(i).ToString())
  If currentCheckBox IsNot Nothing Then
    currentCheckBox.Selected = True
  End If
Next

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 100638

11 Comments

- mona saber

i want the check box list make the user take only one selection not multiple selection
i mean when he chooce item 1 from the check boxlist
after while he change his select and he want to selct item 2 the first selction deleted outomatically with going back to item 1 and unsigned it

- Mike

@mona

If you want a user to make an exclusive selection, use a RadioButtonList instead.

- Katie

Hi,
I first want to thank you very much for this post. I've been looking for a solution to do just this but for the life of me I couldn't get it work!

I adapted your code to pull selected items back in from a sql db and it works great. I have a checkbox list that is being populated by a table that contains all the selections.

I added the adapted code to a test button and after the page loads and I click on the button, it does re-select all the previously selected items.

My problem now is that I need it to automatically do that when the user returns to that page but when I put it in the on load sub, it doesn't work. I'm thinking it is because the checkbox list is being populated with the items at the same time so there isn't anything in the checkbox list when the code to re-select is running.

Do you have any ideas as to how I can get ths to run right after the original checkbox list loads?

Thanks very much for any thoughts.
K

- Mike

@Katie

Force the CheckBoxList to populate by calling MyCheckBoxList.DataBind() before you try to check to see if the values match what the user saved.

- john

Hi Mike,
I am new to alot of this, how to you start this off in .cs. Do you use public void on_inserted(object sender, sqldatasourcestatuseventargs e)? I am having problem with laying it out. I like the way you broke it up, but still don't understand how to lay it out. I am putting the checkboxlist from another table. Can you help?
thanks

- jon

thanks for the great article. Just what I needed. I only have one question. On some of my checkbox lists my last option is an Other, please specify checkbox which also needs a textfield to enter the reason.

currently I am thinking I will just leave the other option off of the list and just add that field manually but that defeats the purpose of a dynamic list.

Any ideas?

- Mike

@John

Turn to design view and click the lightning bolt on the properties panel once you have selected the SqlDataSource control. Find the Inserted event in the list, and double click it. It will generate the handler code for you.

- Mike

@Jon

A textbox is a textbox. You could just see if anyone has entered anything in it.

- Inah

Thank u very much!

- sid

thanks...

- ashok

its really helpful

Recent Comments

dave 20/08/2016 14:57
In response to ASP.NET Web Pages vNext or Razor Pages
Do SimplemembershipProvider in viewpages is supported?...

Steven 18/08/2016 04:40
In response to Entity Framework Code First and Stored Procedures
Can you provide the directives (using statements) you're using for EF7 example?...

yousaid 17/08/2016 22:08
In response to ASP.NET Web Pages vNext or Razor Pages
Increasingly, learning a Microsoft tool is no longer worth the return on investment. Too many tools...

jared 12/08/2016 05:54
In response to ASP.NET Web Pages vNext or Razor Pages
hi mike, just for clarification, is viewpages something different from webpages? is webpages still...

Jocke 08/08/2016 20:37
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Good post! If this was to be implemented in a CMS where users can change the view files, how would I...

cyrus 05/08/2016 19:49
In response to ASP.NET Web Pages vNext or Razor Pages
I think adding these features to webpages make it complicated. msft forget webpages goal so we move...

Curt Smith 27/07/2016 20:38
In response to ASP.NET Web Pages vNext or Razor Pages
I am only slightly disappointed to hear that WebMatrix is officially dead, because I suspected this...

Darshan Raj L G 27/07/2016 13:20
In response to Implementing SQL Server Full-Text Search In An ASP.NET MVC Web Application With Entity Framework
I though it would be more helpful for somebody who wants to work with Entity Framework... please EF...

Satyabrata 25/07/2016 08:09
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Very Interesting!!...

Jerrie Pelser 23/07/2016 05:08
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Very cool concept Mike!...