[英]How to add controls dynamically to ASP.NET form?
我不知道如何使用 C# .net 將控件動態添加到表單中。 任何人都可以幫助我嗎? 我在 vb.net 中知道這一點,但我需要知道 C# 中的語法。
在表單中,以下代碼可以動態添加按鈕:
Button button1 = new Button();
button1.Text = "dynamic button";
button1.Left = 10; button1.Top = 10; //the button's location
this.Controls.Add(button1);
在 Aspx 中
<%@ Reference Control = "WebUserControl1.ascx" %>
您可以在 Cs 文件中使用以下內容來動態加載控件...
if (case)
else
{
WebUserControl1 uc =
(WebUserControl1) Page.LoadControl("WebUserControl1.ascx");
PlaceHolder1.Controls.Add(uc);
}
或者試試這個
Content.Controls.Add(Page.LoadControl("UserControls/InventoryNav.ascx"));
也可以看看:
下面是將控件動態添加到 ASP.NET 表單的代碼。
Label lbl1 = new Label();
lbl1.Text = "Your message here";
Panel panel1= new Panel();
panel1.Controls.Add(lbl1);
下面是可以在某些事件(如頁面加載或 onload)甚至某些用戶操作(如 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();
}
}
請看下面的示例
假設表單名稱是 frmMain。
Button btnSave = New Button();
frmMain.Controls.Add(btnSave)
將控件添加到面板通常是可以接受的,無論是面板已添加到標記中的頁面還是以編程方式。
有關 C# 語法,請參閱以下鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.