I have a problem in ASP.NET 2.0 with the viewstate of my dynamically
added user control. I have reproduced the problem with a very simple
user control and a very simple page.
On my usercontrol is a button and a label. Everytime the button is
clicked a counter which is stored in the viewstate is increased and
displayed in the label.
The code looks something like this:
Expand|Select|Wrap|Line Numbers
- protected void Page_Load(object sender, EventArgs e)
- {
- btnID.Click += new EventHandler(btnID_Click);
- }
- void btnID_Click(object sender, EventArgs e)
- {
- this.Counter+= 1;
- lblAdd.Text = this.Counter.ToString();
- }
- private int Counter
- {
- get { return this.ViewState["counter"] == null ? 0 :
- (int)this.ViewState["counter"]; }
- set { this.ViewState.Add("counter", value); }
- }
user control is loaded and added to a placeholder on my page. When a
postback happens after this, the usercontrol is loaded again in the
Page_Load. This works without any problems: the usercontrol is loaded
and the events of the button on the user control work fine. The code
looks something like this:
Expand|Select|Wrap|Line Numbers
- protected void Page_Load(object sender, EventArgs e)
- {
- btnAddControl.Click += new EventHandler(btnAddControl_Click);
- if (this.Init)
- {
- Test ctrl = this.LoadControl("~/Test.ascx") as Test;
- ctrl.ID = "TEST";
- plcControl.Controls.Add(ctrl);
- }
- }
- void btnAddControl_Click(object sender, EventArgs e)
- {
- Test ctrl = this.LoadControl("~/Test.ascx") as Test;
- ctrl.ID = "TEST";
- plcControl.Controls.Add(ctrl);
- this.Init = true;
- }
- private bool Init
- {
- get { return this.ViewState["init"] == null ? false :
- (bool)this.ViewState["init"]; }
- set { this.ViewState.Add("init", value); }
- }
load, the value is not saved in the viewstate of the user control. I
added a line to the event handler of the btnAddControl, so it looks
like this:
Expand|Select|Wrap|Line Numbers
- void btnAddControl_Click(object sender, EventArgs e)
- {
- Test ctrl = this.LoadControl("~/Test.ascx") as Test;
- ctrl.ID = "TEST";
- ctrl.Counter = 20;
- plcControl.Controls.Add(ctrl);
- this.Init = true;
- }
is not in the viewstate and the counter starts from 0. However when I
add the following line to the Page_Load of the usercontrol, the
Counter is initialized correctly to 20:
Expand|Select|Wrap|Line Numbers
- protected void Page_Load(object sender, EventArgs e)
- {
- this.Counter = this.Counter; //This is the new line!
- btnID.Click += new EventHandler(btnID_Click);
- }
The value 20 of the initialization is in the viewstate, but it is not
saved unless I added the last line the the Page_Load event.
Can anyone help me with this problem or explain why the value is not
saved in the viewstate? Any thoughts on adding user controls
dynamically to a page are appreciated as well.
Kind regards,
Jelle