david arellano
david arellano

Reputation: 3

ASP.Net Button and the onclick event don't work

I make a dynamic table with buttons in they cells, but when i click some button show me this error in console:

Uncaught ReferenceError: bttn_Click is not defined
    at HTMLUnknownElement.onclick (VM51 panel.aspx:1)

this is how i make the button in html and asp.net :

StringBuilder htmlStr = new StringBuilder();
htmlStr.Append("<asp:button onclick='bttn_Click' class='btn btn-warning btn-xs'  ID='Bttn_PDF'>PDF</asp:button>");
PlaceHolder1.Controls.Add(new Literal { Text = htmlStr.ToString() });

and the C#

protected void bttn_Click(object sender, CommandEventArgs e)
{
  Button btn = (Button)sender;
  string btnid = btn.CommandArgument;
  test.Text = btnid;
}

Upvotes: 0

Views: 2141

Answers (1)

Rion Williams
Rion Williams

Reputation: 76547

This is because the onclick event actually expects a Javascript-specific event to be called and you are currently trying to call a server-side event instead. When defining such an event on an actual ASP.NET Button control, you instead want to use the OnClientClick event instead. But this doesn't really matter as you want to target a server-side event and not a client-side one.

Build Your Button Server-side

What you'll likely want to do is create an actual Button control, define a click event handler that points to your method, and then add that control to the page as opposed to building a string:

// Build your button with its specific properties
Button button = new Button();
button.ID = "Bttn_PDF";
button.CssClass = "btn btn-warning btn-xs";
// Wire up its click event
button.Click += bttn_Click;
// Add it to the form
PlaceHolder1.Controls.Add(button);

Upvotes: 1

Related Questions