簡體   English   中英

如何將控件動態添加到 ASP.NET 表單?

[英]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"));

也可以看看:

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

下面是將控件動態添加到 ASP.NET 表單的代碼。

  1. 初始化標簽
  2. 為其分配文本。
  3. 初始化面板
  4. 將標簽對象添加到面板。
     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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM