0

How can i add a asp button with onclick events in a table cell programatically?

This is what i have tried.

TableCell tbBtn = new TableCell();
  Button bt = new Button();
  bt.Text = "Add Books to Database";
  bt.ID = (count++).ToString();
  bt.Click += new EventHandler(btnAddBook);
tbBtn.Controls.Add(bt);

But when the page is loaded, the button was a input type="submit" and it does not have a onclick event at all.

Here is the view source of the button

<input type="submit" name="ctl00$ContentPlaceHolder1$0" 
    value="Add Books to Database" id="ContentPlaceHolder1_0">

How can i make the button to be like an ASP button to runat server and to be able to execute a function when on clicked.

Cheers.

3
  • What you see is correct. A Button does not need an OnClick event. Did you actually click a button to see if btnAddBook was triggered? Commented Aug 22, 2018 at 14:29
  • I tried to add a breakpoint in btnAddBook but it does not hit, so i was wondering if there is something wrong with the onclick events. Commented Aug 22, 2018 at 14:32
  • If you add those buttons to the cell in an IsPostBack check then it wont work. Dynamically added events must be added on each page load, and that includes a PostBack. Commented Aug 22, 2018 at 14:35

1 Answer 1

-1

You have to differentiate between serverside onClick (runs C# code) and clientside onClick (runs javascript).

If you are talking about clientside then you do it like this - if I remember correctly without VS in front of me :)

    Button bt = new Button();
    bt.Attributes.Add("onclick","[your javascript code]";

Hope this helps,

Sign up to request clarification or add additional context in comments.

1 Comment

That is what the OnClientClick property is for.

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.