0

I cannot find the checkboxes within Panel. Here is my code. On page load I add dynamically controls. It loads all controls properly:

if(!Page.IsPostBack){
foreach (var chk in chks)
{
   PlSettings.Controls.Add(new LiteralControl("<div class=\"Controls\">"));

   PlSettings.Controls.Add(chk);

   PlSettings.Controls.Add(new LiteralControl("</div>"));
}
}

On button update, I would like to loop through all controls within panel, and if type of checbox, check if it's checked or not.

foreach (var panelctrl in PlSettings.Controls)
            {

                  if (panelctrl.GetType() == typeof(CheckBox))
                   {
                      var checkbox = (CheckBox)chk;

                      if (checkbox.Checked)
                       {
                                userSettings.Add(Convert.ToInt32(checkbox.ID));
                       }
                   }

            }

For some reason Panel has only one literal control. and no controls within.

2 Answers 2

2

Update the foreach with this code:

// if(!Page.IsPostBack){
foreach (var chk in chks)
{
   PlSettings.Controls.Add(new LiteralControl("<div class=\"Controls\">"));

   PlSettings.Controls.Add(chk);

   PlSettings.Controls.Add(new LiteralControl("</div>"));
}
//}

You must add dynamic controls on every postback. Also, make sure this is done during init or preinit stage.

Sign up to request clarification or add additional context in comments.

Comments

0

Try something like this instead:

foreach (CheckBox chk in PlSettings.Controls.OfType<CheckBox>())
{
    //code here
}

And since these controls are being generated dynamically, you'll need to recreate the controls at every postback. Make sure you assign the same ID to the controls each time too, so that ViewState can reload the checked state.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.