Example of ASP.NET adding controls dynamically

  • 2020-05-16 06:48:37
  • OfStack

There are three Label in the first click page, six in the second click, and nine in the third click, so each click adds three more in the previous state.
My method is that the last state can be saved through Session. One solution is as follows:
Test.aspx key code:
 
<form id="form1" runat="server"> 
<asp:DropDownList ID="DropDownList1" runat="server"> 
<asp:ListItem>1</asp:ListItem> 
<asp:ListItem>2</asp:ListItem> 
<asp:ListItem>3</asp:ListItem> 
</asp:DropDownList> 
<asp:DropDownList ID="DropDownList2" runat="server"> 
<asp:ListItem>a</asp:ListItem> 
<asp:ListItem>b</asp:ListItem> 
<asp:ListItem>c</asp:ListItem> 
</asp:DropDownList> 
<asp:DropDownList ID="DropDownList3" runat="server"> 
<asp:ListItem>A</asp:ListItem> 
<asp:ListItem>B</asp:ListItem> 
</asp:DropDownList> 
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> 
<asp:Panel ID="Panel1" runat="server"> 
</asp:Panel> 
<asp:Button ID="Button2" runat="server" Text=" The last 1 a Button" /> 
</form> 

Test.aspx.cs key code:
 
protected void Page_Load(object sender, EventArgs e) 
{ 
if (Session["Panel1"] != null) 
{ 
int index = this.Form.Controls.IndexOf(Panel1); 
this.Form.Controls.RemoveAt(index); 
Panel1 = Session["Panel1"] as Panel; 
this.Form.Controls.AddAt(index, Panel1); 
} 
} 
protected void Button1_Click(object sender, EventArgs e) 
{ 
for (int i = 0; i < 3; i++) 
{ 
Label label = new Label(); 
DropDownList ddl = this.FindControl("DropDownList" + (i + 1).ToString()) as DropDownList; 
label.Text = ddl.SelectedValue; 
Panel1.Controls.Add(label); 
} 
Literal br = new Literal(); 
br.Text = "<br/>"; 
Panel1.Controls.Add(br); 
Session["Panel1"] = Panel1; 
} 

When the page is sent back, write down the location of Panel1 in the control tree and remove it, then get the last added Panel1 from the Session variable, add it to the original location in the control tree, and continue to add the new Label control from there. The last Button is for testing purposes. The function of 2:1 is to help check whether the added position is correct, and the function of 2 is to check whether the state can be maintained in the last empty postback.

Related articles: