今天被問到如何在ASP.NET 頁面中動態創建一批控件,並且希望在後續代碼 中能訪問到這些動態創建的控件。我用下面的例子來解釋這個問題
頁面文件:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="createbutton" runat="server" Text="批量創建按 鈕"
onclick="createbutton_Click" /><asp:Button ID="displaybutton"
runat="server" Text="顯示動態按鈕的信息" onclick="displaybutton_Click"/>
<asp:Table ID="HolderTable" runat="server"></asp:Table>
</div>
</form>
</body>
</html>
----上面的Table是用來存放動態控件的,用Table是因為它有行和列的概念 ,更易於布局設計。除了Table之外,還可以使用PlaceHolder控件或者Panel控 件
代碼文件:
public partial class _Default : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
CreateControl();
}
protected void createbutton_Click(object sender, EventArgs e)
{
if (ViewState["CreateControl"] == null)
{
ViewState["CreateControl"] = true;
CreateControl();
}
}
void CreateControl() {
///批量創建100個按鈕
///
if (ViewState["CreateControl"]==null) return; // 第一次的時候應該不要創建這些控件
for (int x = 0; x < 10; x++)
{
TableRow row = new TableRow();
for (int y = 0; y < 10; y++)
{
TableCell cell = new TableCell ();
Button bt = new Button();
bt.Text = string.Format(" x= {0},y={1} ", x, y);
bt.Click += new EventHandler (bt_Click);
cell.Controls.Add(bt);
row.Cells.Add(cell);
}
HolderTable.Rows.Add(row);
}
}
void bt_Click(object sender, EventArgs e)
{
Trace.Write("控件動態事件");
((Button)sender).BackColor = System.Drawing.Color.Red;
Response.Write(string.Format("你點擊了該按鈕:{0}", ((Button)sender).Text));
}
/// <summary>
/// 顯示動態創建的控件的信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void displaybutton_Click(object sender, EventArgs e)
{
for (int x = 0; x < 10; x++)
{
TableRow row = HolderTable.Rows[x];
for (int y = 0; y < 10; y++)
{
Button bt = (Button)row.Cells [y].Controls[0];
Response.Write(bt.Text);
}
}
}
}