<span style="font-size:32px;">Html代码如下:</span>
<span style="font-size:32px;">
</span>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<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>
C#代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreateControl();
}
protected void createbutton_Click(object sender, EventArgs e)
{
if (ViewState["CreateControl"] == null)
{
ViewState["CreateControl"] = true;
CreateControl();
}
}
void CreateControl()
{
//批量创建控件
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();
LinkButton lbt = new LinkButton();
lbt.Text = string.Format("x={0},y={1}",x,y);
lbt.Click += new EventHandler(lbt_click);
cell.Controls.Add(lbt);
row.Cells.Add(cell);
}
HolderTable.Rows.Add(row);
}
}
void lbt_click(object sender, EventArgs e)
{
Trace.Write("控件动态事件");
((LinkButton)sender).BackColor = System.Drawing.Color.Red;
Response.Write(string.Format("你点击了该按钮:{0}",((LinkButton)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++ )
{
LinkButton lbt = (LinkButton)row.Cells[y].Controls[0];
Response.Write(lbt.Text);
}
}
}
}
}