Google
Note:
1. enableviewstate = "true" must be added to the ASPX page <% PAGE %> ",
Saves the status of dynamically added controls
2. dynamically added controls should be placed on the container (panel is used here)
3. the ID of the dynamic control must be set. Otherwise, the control cannot be obtained.
Suggestion: Using Asp.net Ajax will provide better user experience
Example:
Test2.aspx: <% @ page Language = "C #" autoeventwireup = "true" codefile = "test2.aspx. cs"
Inherits = "Test2" Title = "untitled page" enableviewstate = "true" %>
<Asp: Panel id = "panel2" runat = "server" Height = "50px" width = "446px">
<Asp: Label id = "label1" runat = "server" text = "name1:"> </ASP: Label>
<Asp: textbox id = "textbox1" runat = "server"> </ASP: textbox>
<Asp: Label ID = "Label2" runat = "server" Text = "Address1:"> </asp: Label>
<Asp: TextBox ID = "TextBox2" runat = "server" Width = "149px"> </asp: TextBox> <br/>
</Asp: Panel>
<Asp: Button ID = "btnAddAjax" runat = "server" Text = "Add" OnClick = "btnAddAjax_Click"/>
<Asp: Button id = "btnShow" onclick = "btnShow_Click" runat = "server" Text = "Show"/>
<Asp: Label id = "lblMsg" runat = "server"> No Value </asp: Label>
Test2.aspx. cs
Using System;
Using System. Data;
Using System. Configuration;
Using System. Collections;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Public partial class Test2: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
If (ViewState ["txtName2"]! = Null & (bool) ViewState ["txtName2"])
{
Createmycontrols ();
}
}
Protected void btnaddajax_click (Object sender, eventargs E)
{
Createmycontrols ();
}
Protected void btnshow_click (Object sender, eventargs E)
{
If (viewstate ["txtname2"]! = NULL)
{
Textbox txtname2 = panel2.findcontrol ("txtname2") as textbox;
If (txtName2! = Null)
LblMsg. Text = "Name2 =" + txtName2.Text;
}
If (ViewState ["txtAddr2"]! = Null)
{
TextBox txtAddr2 = Panel2.FindControl ("txtAddr2") as TextBox;
If (txtAddr2! = Null)
LblMsg. Text + = "Addr2 =" + txtAddr2.Text;
}
}
Private void CreateMyControls ()
{
Label lblName2 = new Label ();
LblName2.Text = "Name2 :";
TextBox txtName2 = new TextBox ();
// Set the ID. Otherwise, the value cannot be obtained.
TxtName2.ID = "txtName2 ";
// Visible State; otherwise, the dynamically added control will not be seen after PostBack
ViewState ["txtName2"] = true;
Label lblAddr2 = new Label ();
LblAddr2.Text = "Addr2 :";