Asked today how to dynamically create a batch of controls on a ASP.net page, and you want to have access to these dynamically created controls in subsequent code. I use the following example to explain this problem
Paging File:
<title></title>
<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>
The table above----is used to hold the dynamic control, with the table because it has the concept of row and column, easier to layout design. In addition to table, you can also use the placeholder control or the Panel control
Code files:
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 () {
///Batch Create 100 buttons
///
if (viewstate["CreateControl"]==null) return; The first time you should not create these controls
for (int x = 0; x < x. x + +)
{
TableRow row = new TableRow ();
for (int y = 0; y < 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 ("Control dynamic event");
(Button) sender). BackColor = System.Drawing.Color.Red;
Response.Write (String. Format ("You clicked the button: {0}", (button) sender). Text));
}
///<summary>
///displays information for dynamically created controls
///</summary>
<param name= "Sender" ></param>
///<param name= "E" ></param>
protected void Displaybutton_click (object sender, EventArgs e)
{
for (int x = 0; x < x. x + +)
{
TableRow row = holdertable.rows[x];
for (int y = 0; y < y++)
{
button BT = (button) row. Cells [y]. Controls[0];
Response.Write (BT. Text);
}
}
}
}