18.3.14

Checkboxlist no values

Can't compare values in a checkboxlist to those from a datasource / datatable?

Make sure the checkboxlist listitems actually have values first. They won't have values on page load - you might need to run your compare script under the DataBound event instead...

HTML:

<asp:CheckBoxList runat="server" ID="interest" OnDataBound="interest_databound" DataSourceID="dsInterest" DataTextField="InterestDescription" DataValueField="InterestID">
</asp:CheckBoxList>

Code-behind:

protected void interest_databound(object sender, EventArgs e) {
   int PersonID = 5;
   SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["db"].ConnectionString);
   SqlCommand cmd = new SqlCommand("SELECT PersonID, InterestID, InterestDescription FROM Table where PersonID = '" + PersonID + "'", con);
   con.Open();
   SqlDataReader dr = cmd.ExecuteReader();
   while (dr.Read()) {
      ListItem currentCheckBox = interest.Items.FindByValue(dr["InterestID"].ToString());
      if (currentCheckBox != null) {
         currentCheckBox.Selected = true;
      }
   }
   dr.Dispose();
   con.Dispose();
   cmd.Dispose();
}

1 comment:

Tora said...

Well I never knew!