1.页面上放一个容器,这样有目的性,且范围小,html:
<asp:Panel runat="server" ID="panelContent">
<asp:Button runat="server" CommandArgument="writeok" Text="btnok" OnClick="Button_Click" />
</asp:Panel>
2.服务器代码:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 1; i < 5; i++)
{
Button btn = new Button();
btn.CommandArgument = "btn" + i.ToString();
btn.Text = "Button" + i.ToString();
btn.Click += new EventHandler(Button_Click);
this.panelContent.Controls.Add(btn);
}
}
/// <summary>
/// 事件
/// </summary>
/// <param name="sender">事件发起者</param>
/// <param name="e">事件参数</param>
protected void Button_Click(object sender, EventArgs e)
{
Response.Write(" 这是" + ((Button)sender).CommandArgument + "事件");
}
一般对页面上某个地方按钮比较多且它们的功能操作相似的按钮集合做这样的处理,毕竟每次按钮提交都会重绘页面的