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 #.
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);
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
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(); } }
See example below.
allows you to name the form name frmMain.
Button btnSave = New Button(); frmMain.Controls.Add(btnSave)
Below is the code for dynamically adding controls to an ASP.NET form.
Add the label object to the panel.
Shortcut lbl1 = new shortcut ();lbl1.Text = "Your message here";Panel panel1 = new panel ();panel1.Controls.Add (lbl1);
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