I am trying to add an instance of UserControl each time on button_click event, it works for the first time only.
I am adding IDs to user control by appending integers from ViewState.
Why does it not add work for subssequent clicks.
Here is the simplified version with the same behavoir.
protected void Button1_Click(object sender, EventArgs e)
{
HtmlButton btnClick = new HtmlButton();
btnClick.ID = "bt" + Append.ToString();
btnClick.InnerText = "Button 1";
MainArea.Controls.Add(btnClick);
}
Ok, now that the code is posted, I can confirm the problem.
Each time you click the button, a postback is made. On postback, you add the new button, with the name containing your count. But, when the page re-renders on the second button click, it loses all the controls you’ve added and just adds back the one (from this postback’s button click).
So what you want to do is set up a loop, something like:
And that will add one button per previous click, assuming that “Append” is some kind of counter that you’re storing in viewstate.
Now that’s also assuming you wanted one instance of the control per click. Which is what I think you said.