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:
- 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).
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);
}
}
}
lblerr.Text = c.ToString();withlblerr.Text = ((CheckBox) c).Text;Controlscollection 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.