this.Controls.Add(new CheckBox{ Checked = true; })
When I add this in the page_load. It works, it adds the checkbox and it is visible.
A little different approach:
var button = new CheckBox{ Checked = true; }
globals.button = button;
this.Controls.Add(button);
Globals is a class with a checkbox property on which I want to set the checkbox in the hope of retrieving it’s a data after pressing a button.
public static CheckBox button { get; set; }
However, when a button is pressed, the control has vanished of my screen and the button in my globals class has not been updated with any changes I have made to the checkbox.
How can I change the checked state of a checkbox and catch it’s current state when I perform a button.click event?
You must re-create dynamic controls on every postback, they wont magically re-appear because every request is a new instance of the
Pageclass.See my previous post on this subject, it is using a user control but the idea is just the same.
And another
You must add the control before Page_Load
I normally do it in the overridden
CreateChildControlsbut some people usePage_Init.see this article
Update
This is a very simple way to add the checkbox dynamically, that preserves state/value when the button is clicked.
Then Code Behind