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

4.36 (53 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

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

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

Ghazanfar 30/01/2016 06:43
In response to Getting Started with ASP.NET MVC 5 using Visual Basic
Nice working. Please keep it up to convert csharp code into vb.net. Its very helpful for vb...

sara 29/01/2016 09:39
In response to Simple Login and Redirect for ASP.NET and Access
Hi there, I am trying to validate and check for inputs entered. When I don't enter any inputs and...

Martin Thatcher 28/01/2016 17:28
In response to MVC 5 with EF 6 in Visual Basic - Advanced Entity Framework Scenarios
A small typo I think. In the code section that begins Function Index(ByVal SelectedDepartment As As...

Suresh_thefame 28/01/2016 08:03
In response to Sessions and Shopping Carts
Helpful....

Andrey Kurdyumov 28/01/2016 05:47
In response to ASP.NET 5: Uploading files with ASP.NET MVC 6
@Lee IFormFile has OpenReadStream(): Stream method...

Alisa 27/01/2016 18:37
In response to A Better Way To Export Gridviews To Excel
Thanks for this example! I am also asking about the date fields having to be re-formatted when the a...

Dan Buckley 27/01/2016 00:47
In response to What ASP.NET Can And Cannot Do
New to all things programming, this was very helpful and clear. Please write more....

satyabrata 26/01/2016 16:16
In response to Request.Form Is Empty When Posting To ASPX Page
Thank you....

david sanchez 26/01/2016 09:51
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Thanks! This line " <img src="~/images/@Model.FilePaths.First(f => f.FileType == alt="" />" an...

Bryon 25/01/2016 15:06
In response to Windows Authentication With ASP.NET Web Pages
Was hoping this would help solve the issues I'm having. Then I saw the dates and new it was too old....