How to add controls dynamically to an ASP.NET form?

I don't know how to add controls dynamically to a form using C # .net. Can someone help me? I know this with vb.net, but I need to know the syntax in C #.

+6
c # controls webforms
source share
6 answers

In the form, the following code can dynamically add a button:

Button button1 = new Button(); button1.Text = "dynamic button"; button1.Left = 10; button1.Top = 10; //the button location this.Controls.Add(button1); 
+6
source share

In aspx

 <%@ Reference Control = "WebUserControl1.ascx" %> 

U can use the following in a Cs file to dynamically control this parameter ...

 if (case) else { WebUserControl1 uc = (WebUserControl1) Page.LoadControl("WebUserControl1.ascx"); PlaceHolder1.Controls.Add(uc); } 

or try this

  Content.Controls.Add(Page.LoadControl("UserControls/InventoryNav.ascx")); 

You can also see:

http://aspalliance.com/565

http://samuelmueller.com/2008/12/dynamicloader-plugin-dynamically-loading-asp-net-user-controls-with-jquery

http://forums.asp.net/p/1222567/2826338.aspx

+3
source share

Below is the code that can be called on some events, such as page loading or loading, or even some user actions, such as onclick.

 protected void add_button(Button btn) { try { panel1.Controls.Add(btn); // Add the control to the container on a page } catch (Exception ee) { lblError.Text = ee.Message.ToString(); } } 
+2
source share

See example below.

allows you to name the form name frmMain.

 Button btnSave = New Button(); frmMain.Controls.Add(btnSave) 
+2
source share

Below is the code for dynamically adding controls to an ASP.NET form.

  • Initialize Label
  • Assign text to it.
  • Initialize Panel
  • Add the label object to the panel.

    Shortcut lbl1 = new shortcut ();
    lbl1.Text = "Your message here";
    Panel panel1 = new panel ();
    panel1.Controls.Add (lbl1);

+2
source share

In general, it’s acceptable to add controls to a panel, whether the panel is added to the page in a layout or programmatically.

See link for C # syntax

+1
source share

All Articles