0

I am trying to call btn_Click from the dynamically added button using HtmlTextWriter. But it will not trigger. I am unable to add event handler in code behind to the button as it is not a ASP.NET button.

    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();
    }
}
4
  • Can you provide the event method where you try to do this? Commented Mar 12, 2015 at 11:55
  • Can you add this lines of code in on init event? protected void Page_Init(object sender, EventArgs e) { } Also, you are constrainted to use HtmlTextWritter? Commented Mar 12, 2015 at 12:19
  • It doesn't work in Page_Init. Any recommended method instead of HtmlTextWriter? Commented Mar 12, 2015 at 12:30
  • I posted an answer with an recommended alternative, please also read the first paragraph. Commented Mar 12, 2015 at 13:14

1 Answer 1

1

Trying to translate your code to map attributes to a button i noticed that you have writer.AddAttribute("onserverclick", "btn_Click") and you should have writer.AddAttribute("onclick", "btn_Click").

Also you can add a button dynamically in your page by appending it to another control from the page.

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
        }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.