SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Sep 2005
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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

  2. #2
    SitePoint Enthusiast aamelyan's Avatar
    Join Date
    Feb 2006
    Location
    Milwaukee, WI
    Posts
    57
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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);
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •