Iterating through CheckBoxList To Insert Records

Having inserted a record, you want to retrieve the newly created record's ID number, then iterate over a collection of items, such as a CheckBoxList to insert additional information relating to the record.

NOTE: the CheckBoxList exposes an Items collection, and it is the Selected property that needs to be tested for true or false to determine which items were checked. This is different from a single CheckBox control, whose Checked property needs to be tested.

protected void dsAddArticle_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
  int ArticleID = Convert.ToInt32(e.Command.Parameters["@ArticleID"].Value);
  CheckBoxList chkbx = (CheckBoxList)FormView1.FindControl("chkGetCategories");
  string connectionString = Utils.GetConnString();
        
  using (SqlConnection conn = new SqlConnection(connectionString))
  {
   using (SqlCommand cmd = new SqlCommand("AddCategoriesToArticle", conn))
    {
      cmd.CommandType = CommandType.StoredProcedure;
      conn.Open();
      for (int i = 0; i < chkbx.Items.Count; i++)
        {
          if (chkbx.Items[i].Selected)
            {
              cmd.Parameters.AddWithValue("@CategoryID", chkbx.Items[i].Value);
              cmd.Parameters.AddWithValue("@ArticleID", ArticleID);
              cmd.ExecuteNonQuery();
              cmd.Parameters.Clear();
            }
        }
    }
  }
}

You might also like...