0

I have generated checkboxes dynamically and added them to a panel on a button click with below code.

foreach (string filename in filepaths)
{
  CheckBox chk = new CheckBox();
  chk.Text = Path.GetFileName(filename.ToString());

  Panel1.Controls.Add(chk);
  Panel1.Controls.Add(new LiteralControl("<br>"));                  
}

Now the problem is I couldn't access the checked values on another button with below code

if (!IsPostBack) {
foreach(Control c in Panel1.Controls) {
    if ((c is CheckBox) && ((CheckBox) c).Checked) {
        lblerr.Text = c.ToString();
    }
  }
}

What I found is on button click the page getting loaded so controls in panel returns null. Can anyone explain how to get the checked values.

Thanks in advance.

2
  • Try replacing this line lblerr.Text = c.ToString(); with lblerr.Text = ((CheckBox) c).Text; Commented Nov 24, 2015 at 17:00
  • 1
    As the previous comment notes, even if you get the Controls collection to be non-empty, you will still have a problem in your code to get the text. But presumably you want to fix the collection issue first. You should provide a minimal reproducible example that reproduces the problem; as stated, there are too many possible answers. Commented Nov 24, 2015 at 17:03

1 Answer 1

0

When creating any kind of System.Web.UI.WebControl class problematically, it does not implicitly get re-created when the page is rebuilt during post back. You must call the method that creates the controls again in PageLoad:

protected void Page_Load(object sender, EventArgs e)
{
    if(!this.IsPostback)
        BuildCheckBoxes();
}
private void BuildCheckBoxes()
{
    foreach (string filename in filepaths)
    {
      CheckBox chk = new CheckBox();
      chk.Text = Path.GetFileName(filename.ToString());

      Panel1.Controls.Add(chk);
      Panel1.Controls.Add(new LiteralControl("<br>"));                  
    }
}

This must be done in PageLoad, so that the controls exist when the ViewState is restored. Otherwise, .NET will discard the view state for the controls that "no longer exist".

Keep in mind that this will create overhead on your PageLoad event, if you are building a large number of controls. One way to mitigate this is to stuff controls into the server's cache, but there are a couple of very important things to note when using this method:

  1. The property this.Page.Cache is NOT local to the page. Anything you put in here is shared across the whole of the App Pool (even the MSDN page on this property is misleading).
  2. Each value that you put in must be referenced by a specific key that is unique for each user's session (since, as #1 points out, this cache is global across all sessions). This means the key should include something that uniquely identifies the current session, such as the session key.

    private int DynCheckBoxCount
    {
        get { return (int)this.ViewState["DynCheckBoxCount"]; }
        set { this.ViewState["DynCheckBoxCount"] = value; }
    }
    private void BuildCheckBoxes()
    {
        if (!this.IsPostBack)
        {
            int i = 0;
            foreach (string filename in filepaths)
            {
                CheckBox chk = new CheckBox();
                chk.Text = Path.GetFileName(filename); // Don't do a .ToString() on a string.  It's unnecessary, ugly code, and opens the door for NullReferenceExceptions.
                chk.Style.Add(HtmlTextWriterStyle.Display, "block");
                Panel1.Controls.Add(chk);
                string key = string.Format("{0}_{1}", this.Session.SessionID, i++);
                this.Page.Cache[key] = chk;
            }
            this.DynCheckBoxCount = i;
        }
        else
        {
            for (int i = 0; i < this.DynCheckBoxCount; i++)
            {
                string key = string.Format("{0}_{1}", this.Session.SessionID, i);
                CheckBox chk = (CheckBox)this.Page.Cache[key];
                this.Panel1.Controls.Add(chk);
            }
        }
    }
    
Sign up to request clarification or add additional context in comments.

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.