html - Creating Button and OnClick Event from c# side -

im creating a button from c# side like this:

content += "<button class='btn btn-info' runat='server' style='margin-left:4%' id='Like" + dr[0] + "' onclick='likeClick'>";

And the event is really simple i just want to see if its working:

protected void likeClick(object sender, EventArgs e)
    content = sender.ToString();

But when i click the button it doesn't trigger the event, I put a break point in the event and I debugged but it didn't start the fucntion. I opened Inspect Element in the browser and clicked the button. It showed me this:

enter image description here

What am I doing wrong here?

1 Answer

  1. Bill- Reply


    I understand that you want to create a Button server control dynamically. The way, you are creating is wrong. You have to instantiate a Button object, declare the Click event and add it to your page. Also, since it is a dynamically created control, it will required to be re-created on every postback. Here is a sample code on similar scenario:

    <!DOCTYPE html>
    <html xmlns="">
    <head runat="server">
        <form id="form1" runat="server">
            <asp:PlaceHolder runat="server" ID="phControl" />
        protected void Page_Load(object sender, EventArgs e)
            Button btnButton = new Button();
            btnButton.Style.Add("margin-left", "4%");
            btnButton.ID = "like"+ dr[0];
            btnButton.Text = "Like";
            btnButton.Click += BtnButton_Click;
        private void BtnButton_Click(object sender, EventArgs e)
            string content = sender.ToString();

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>