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

后端 未结 6 2095
盖世英雄少女心
盖世英雄少女心 2020-11-30 07:53

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 s

6条回答
  •  -上瘾入骨i
    2020-11-30 08:49

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

        
        
    

    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 YrStrList = new List();
            // 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.

提交回复
热议问题