Search code examples
c#asp.nethtmlhtmltextwriter

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart


I am creating a CheckBoxList in a class file and am using an HTMLTextWriter to render the control.

I'm using the following code to store the selected values in a string:

string YrStr = "";
for (int i = 0; i < YrChkBox.Items.Count; i++)
{
    if (YrChkBox.Items[i].Selected)
    {
        YrStr += YrChkBox.Items[i].Value + ";"; 
    }
}

I stepped through the code and it doesn't seem to hit the inside of the if statement & the selected value attribute is false every time ... Anyone have an idea of how I can address this?

I populate it using the following:

 YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));

Solution

  • In your ASPX page you've got the list like this:

        <asp:CheckBoxList ID="YrChkBox" runat="server" 
            onselectedindexchanged="YrChkBox_SelectedIndexChanged"></asp:CheckBoxList>
        <asp:Button ID="button" runat="server" Text="Submit" />
    

    In your code behind aspx.cs page, you have this:

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Populate the CheckBoxList items only when it's not a postback.
                YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));
                YrChkBox.Items.Add(new ListItem("Item 2", "Item2"));
            }
        }
    
        protected void YrChkBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Create the list to store.
            List<String> YrStrList = new List<string>();
            // Loop through each item.
            foreach (ListItem item in YrChkBox.Items)
            {
                if (item.Selected)
                {
                    // If the item is selected, add the value to the list.
                    YrStrList.Add(item.Value);
                }
                else
                {
                    // Item is not selected, do something else.
                }
            }
            // Join the string together using the ; delimiter.
            String YrStr = String.Join(";", YrStrList.ToArray());
    
            // Write to the page the value.
            Response.Write(String.Concat("Selected Items: ", YrStr));
        }
    

    Ensure you use the if (!IsPostBack) { } condition because if you load it every page refresh, it's actually destroying the data.