11

I do not know how to add controls dynamically to the form using C# .net. Can anyone help me? I know this with vb.net but I need to know the syntax in C#.

meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
SunilRaj
  • 169
  • 1
  • 2
  • 7

6 Answers6

6

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

Button button1 = new Button();
button1.Text = "dynamic button";
button1.Left = 10; button1.Top = 10;  //the button's location
this.Controls.Add(button1);
meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
Jerry
  • 435
  • 4
  • 12
  • This is how I do it. You can also add your button to some other control than this, just in case. – Marcel Oct 17 '13 at 08:02
5

In Aspx

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

U can use the following in the Cs file to laod the control dynamically...

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"));

Can also have a look at:

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

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Navish Rampal
  • 482
  • 1
  • 5
  • 9
4

Below is the code to add controls dynamically to ASP.NET form.

  1. Initialize a label
  2. Assign text to it.
  3. Initialize a panel
  4. Add the label object to the panel.
     Label lbl1 = new Label();
     lbl1.Text = "Your message here";
     Panel panel1= new Panel();
     panel1.Controls.Add(lbl1);
Serkan Arslan
  • 13,158
  • 4
  • 29
  • 44
Billy Samuel
  • 672
  • 2
  • 6
  • 21
3

Below is the code that can be called on some events like page load or onload or even some user action like 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();
   }
}
Brad Larson
  • 170,088
  • 45
  • 397
  • 571
SunilRaj
  • 169
  • 1
  • 2
  • 7
3

Please see the below sample

lets say forms name is frmMain.

Button btnSave = New Button();
frmMain.Controls.Add(btnSave)
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Thanigainathan
  • 1,505
  • 14
  • 25
1

It's generally acceptable to add the controls to a panel, be it that the panel has been added to the page in the markup or programmatically.

See the following link for the C# syntax

Pieter Germishuys
  • 4,828
  • 1
  • 26
  • 34