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

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

Date Posted: Sunday, June 3, 2007 10:56 PM
Last Updated:
Posted by: Mikesdotnetting
Total Views to date: 67365

10 Comments

Thursday, June 18, 2009 5:25 PM - 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

Friday, June 19, 2009 7:49 AM - Mike

@mona

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

Sunday, August 2, 2009 12:01 PM - 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

Sunday, August 2, 2009 10:54 PM - 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.

Thursday, January 21, 2010 7:20 PM - 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

Wednesday, February 3, 2010 3:38 PM - 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?

Wednesday, February 3, 2010 7:16 PM - 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.

Wednesday, February 3, 2010 7:16 PM - Mike

@Jon

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

Monday, June 11, 2012 10:07 PM - Inah

Thank u very much!

Monday, September 3, 2012 8:32 AM - sid

thanks...
Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

Gautam 11/20/2014 8:01 AM
In response to I'm Writing A Book On WebMatrix
Hello Mike, I read your book, loved it! However, I have a few request/suggestions: 1) an example...

Bret Dev 11/19/2014 8:39 PM
In response to The Difference Between @Helpers and @Functions In WebMatrix
Excellent post! One concern - where can you place global @Functions code within an MVC project to Is...

Rob Farquharson 11/19/2014 4:28 PM
In response to iTextSharp - Links and Bookmarks
How can I place text at an absolute position on the page? Also, how can I rotate text?...

Andy 11/17/2014 8:08 PM
In response to MVC 5 with EF 6 in Visual Basic - Sorting, Filtering and Paging
Hello I'm testing your sorting instructions above. This is great and I was able to get it to work...

Gautam 11/17/2014 5:51 PM
In response to WebMatrix - Database Helpers for IN Clauses
Hi Mike, I am very new to programming: In the above example if I want to use a delete button the...

donramon 11/17/2014 3:22 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Congratulations on your new website look and the excellent articles. Thank you!...

Gautam 11/17/2014 11:26 AM
In response to Looking At The WebMatrix WebGrid
Hi Mike, I add the jquery script at the end of my html file.. when ajax attribute is added to the be...

Chet Ripley 11/15/2014 6:57 PM
In response to Adding A New Field
It appears the command is case sensitive. I had the same issue as Cameron. When I changed the to it...

Alvin 11/14/2014 12:49 PM
In response to Razor Web Pages E-Commerce - Adding A Shopping Cart To The Bakery Template Site
Great article Mike! When do you plan to extend the bakery shopping cart beyond this point?...

Gautam 11/14/2014 10:16 AM
In response to Web Pages - Efficient Paging Without The WebGrid
to get the count can we use only the below sql, why to join category and author table var sql =...