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

You might also like...