Introduction:
In my previous
article I have explained about What is View State? How to Store and retrieve
values from View State. In this article I am going to explain how to add controls
programmatically on run time.
Explanation:
This
example adds a text box and button to a Web Forms page at run time. It also
dynamically binds an event handler to the button's Click event. The handler displays the values
of the dynamically generated text box.
The
controls are added into a Panel Web server control, which acts as a placeholder. The
controls are separated in the panel with line breaks (HTML <BR>
elements), which are added to the panel using the LiteralControl control.
Below is the code.
private void Page_Load(object sender,
System.EventArgs e)
{
if (!IsPostBack)
AddControls();
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (ViewState["controsladded"] == null)
AddControls();
}
private void AddControls()
{
TextBox dynamictextbox
= new TextBox();
dynamictextbox.Text = "sample
text";
dynamictextbox.ID = "txtdynamic";
Button dynamicbutton
= new Button();
dynamicbutton.Click += new System.EventHandler(btndynamic_Click);
dynamicbutton.Text = "Dynamic
Button";
Panel1.Controls.Add(dynamictextbox);
Panel1.Controls.Add(new LiteralControl("<BR>"));
Panel1.Controls.Add(new LiteralControl("<BR>"));
Panel1.Controls.Add(dynamicbutton);
ViewState["controlsadded"] = true;
}
private void btndynamic_Click(Object sender,
System.EventArgs e)
{
TextBox tb
= new TextBox();
tb = (TextBox)(Panel1.FindControl("txtdynamic"));
Label1.Text = tb.Text;
}
Comments
Post a Comment