单击动态添加按钮时,在后面的代码中触发事件

时间:2015-03-12 11:47:49

标签: c# asp.net button event-handling dynamically-generated

我正在尝试使用btn_Click从动态添加的按钮中调用HtmlTextWriter。但它不会触发。我无法在代码中添加事件处理程序,因为它不是ASP.NET按钮。

    protected void btn_Click(object sender, EventArgs e)
    {
         WindowJavaScript.Alert("halo");
    }

protected void PageLoad(object sender, EventArgs e)
{
    //some checking hee to determine whether user is admin or not.
    if(isAdmin)
    {
         writer.AddAttribute(HtmlTextWriterAttribute.Class, "nav navbar-nav navbar-right");
         writer.RenderBeginTag(HtmlTextWriterTag.Ul);
         writer.RenderBeginTag(HtmlTextWriterTag.Li);

         writer.AddAttribute(HtmlTextWriterAttribute.Class, "navbar-brand");
         writer.AddAttribute("runat", "server");
         writer.AddAttribute(HtmlTextWriterAttribute.Id, "admin_B");
         writer.AddAttribute("onserverclick", "btn_Click");
         writer.RenderBeginTag(HtmlTextWriterTag.Button);

         writer.Write("Admin");
         writer.RenderEndTag();
         writer.RenderEndTag();
         writer.RenderEndTag();
    }
}

1 个答案:

答案 0 :(得分:1)

尝试将代码转换为地图属性到按钮时我注意到您有writer.AddAttribute("onserverclick", "btn_Click")并且您应该writer.AddAttribute("onclick", "btn_Click")

此外,您可以通过将页面附加到另一个控件来动态添加按钮。

protected void PageLoad(object sender, EventArgs e)
{
        //some checking hee to determine whether user is admin or not.
        if (isAdmin)
        {
            var btnAdmin = new Button();
            btnAdmin.Click += btn_Click;
            btnAdmin.Text = "Admin";
            btnAdmin.ID = "admin_B";

            otherControl.Controls.Add(btnAdmin); // you need to create otherControl on page
        }
}