Looping through a check box list in C#

Hello everyone,

I’m working on a .aspx page written in C# that includes a check box list. I want to be able to read the values of selected check boxes in the list, put them into a string and then write the content of the string to an Access database.

The problem that I’m having is that the code I’ve written to loop through the check box list doesn’t write the selected values to the string.

Here is the code that creates the check box list:

<asp:CheckBoxList ID=“chklBidType” runat=“server”>
<asp:ListItem Text=”Fixtures" Value=“FIXT” />
<asp:ListItem Text=”Fixtures" Value=“FIXT” />
<asp:ListItem Text=“Furniture” Value=“FURN” />
<asp:ListItem Text=“Equipment” Value=“EQUIP” />
<asp:ListItem Text=“IT for Curriculum use” Value=“Curric IT” />
<asp:ListItem Text=“IT for Admin use” Value=“Admin IT” />
<asp:ListItem Text=“Premises” Value=“PREM” />
</asp:CheckBoxList>

This is the code that is supposed to loop through the checkbox list and create the string:

strBidType = “”;
foreach (ListItem cBox in chklBidType.Items)
{
if (cBox.Selected)
{
strBidType += cBox.Value + " / ";
}
}

I also tried this:

strBidType = “”;
for (int counter = 0; counter < chklBidType.Items.Count; counter++)
{
if (chklBidType.Items[counter].Selected)
{
strBidType += chklBidType.Items[counter].Value + " / ";
}
}

In both cases, strBidType is only returned as a / character with a space before and after, even if more than one check box in chklBidType is selected.

Can anyone spot what I’m doing wrong?

Thanks,
Tom

What event do you use to access selected values?

I tried your code and it works fine for me.
Leave everything like this on your page and add a button control to it. Add this code to your code behind file and try clicking button.

protected void Button1_Click(object sender, EventArgs e) {
string strBidType = “”;
foreach(ListItem cBox in chklBidType.Items) {
if(cBox.Selected) {
strBidType += cBox.Value + " / ";
}
}

    Response.Write(strBidType);
}