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:
Last Updated:
Posted by:
Total Views to date: 77053

10 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...
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 I end up deleting quite a lot. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Requests to fix your code (post a question to forums.asp.net instead, please)
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam

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

faysal 3/3/2015 11:46 AM
In response to Inline Editing With The WebGrid
Nice one can you please tell us how we can do ad and delete functionality in this. for e.g if i on...

Fairoze Mohamed Musthafa 3/2/2015 8:33 AM
In response to Date formatting in VBScript
Appreciated !!!!...

mahdi 3/1/2015 10:16 AM
In response to Getting the identity of the most recently added record
Great Article....

Sohrab 2/28/2015 12:53 PM
In response to Displaying One-To-Many Relationships with Nested Repeaters
hi.this was very usefull for me.after spending 6 hours I could find best answer for my alot....

Abolfazl RoshanZamir 2/28/2015 10:36 AM
In response to Date Formatting in C#
very informative... thanks for sharing sir......

Oscar Duran 2/27/2015 2:00 PM
In response to How To Check If A Query Returns Data In ASP.NET Web Pages
Thank you very much Mike, this post has been very useful to me....

lama 2/27/2015 1:46 PM
In response to iTextSharp - Working with Fonts
thanks alot!! is it possible to add line height value to a paragraph ?...

Oded Dror 2/27/2015 5:23 AM
In response to MVC 5 with EF 6 in Visual Basic - Creating an Entity Framework Data Model
Hi there, Where I can find Contoso University Database? Thanks, Oded Dror...

hosein ey 2/25/2015 1:56 PM
In response to ASP.NET MVC 5 with EF 6 - Working With Files
tnx for this article do you think next version of entityframework support's the sql server and ?...

Saywer Ford 2/25/2015 5:15 AM
In response to Optimising ASP.NET Web Pages Sites - Bundling And Minification
Great Article. I did everything right and working fine. How about page specific js files. Lets I...