Next, the controls will be created:
var newTextbox = new Textbox(); var newLabel = new Label();
You can set the properties you need, etc.
Then find somewhere on your page to add them, let's say you have a panel named panel1, and then do the following:
panel1.Controls.Add(newTextbox); panel1.Controls.Add(newLabel);
However, doing this will not work after the postback - you need to recreate the dynamic controls on the back.
Say you have the following page:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" Text="Button" /> </div> </form> </body> </html>
When you perform the postback, only those controls that are defined on the page above will be created for you. The controls you added dynamically must be re-created by you (for example, in Page_Load).
To do this, the easiest way is to remember the total number of controls that you added to the viewstate, and then add that many controls return when a postback occurs.
The following should start:
using System; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) {
source share