Checking boxes in a C# ASP checkbox list using values from a database

Suppose you have an ASP checkbox list and you need to check the boxes using data returned from the information storage.

You have a couple of ways the data could have been stored. If each checkbox option is a separate field in the database, you could go with a simple loop, but if they have been stored in one field, you need to put some programming power into it.

Here’s a scenario. I have a “seasons” checklist. There are values stored in the db that the user selected. For example if they chose Summer and Fall, the db string “seasons” would contain “Summer Fall”.

<asp:CheckBoxList ID="CheckBoxListSeasons" runat="server">
 <asp:ListItem>Summer</asp:ListItem>
 <asp:ListItem>Fall</asp:ListItem>
 <asp:ListItem>Winter</asp:ListItem>
 <asp:ListItem>Spring</asp:ListItem>
 </asp:CheckBoxList>

In order to display the list with the Summer and Fall boxes checked, I would do this:

string seasons = "Summer Fall"
for (int i = 0; i < CheckBoxListSeasons.Items.Count; i++)
 {

if (seasons.Contains(CheckBoxListSeasons.Items[i].Value))
 {

CheckBoxListSeasons.Items[i].Selected = true;
 }
 } // end checkbox loop

 

 

 

Leave a Reply