【发布时间】:2011-06-04 11:54:09
【问题描述】:
我不知道如何使用 C# .net 向表单动态添加控件。谁能帮我?我通过 vb.net 知道这一点,但我需要知道 C# 中的语法。
【问题讨论】:
标签: c# asp.net webforms controls
我不知道如何使用 C# .net 向表单动态添加控件。谁能帮我?我通过 vb.net 知道这一点,但我需要知道 C# 中的语法。
【问题讨论】:
标签: c# asp.net webforms controls
在表单中,以下代码可以动态添加按钮:
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);
【讨论】:
请看下面的示例
假设表单名称是 frmMain。
Button btnSave = New Button();
frmMain.Controls.Add(btnSave)
【讨论】:
下面是可以在某些事件(例如页面加载或 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();
}
}
【讨论】:
将控件添加到面板通常是可以接受的,无论是面板已通过标记或编程方式添加到页面。
请参阅以下link 了解 C# 语法
【讨论】: