I'm trying to create a button dynamically on asp.net,but I can't add the event to it.What is wrong or missing below?
Thanks in advance
$
Button btn2 = new Button();
btn2.ID = "btnEdit";
btn2.Text = "Edit Member";
btn2.Click += new EventHandler(btnEdit_Click);
form1.Controls.Add(btn2);
I also tried like this:
$
Button btn2 = new Button();
btn2.ID = "btnEdit";
btn2.Text = "Edit Member";
btn2.Attributes.Add("OnClick","btnEdit_Click);
form1.Controls.Add(btn2);
Create a method for adding all Your dynamical controls as below
and then call that method in Page_Load() Event & out side of the IsPostBack block as below
because for dynamically added control's view state will not load before Page_Load() evnt. go through this link for more info http://msdn.microsoft.com/en-us/library/vstudio/hbdfdyh7(v=vs.100).aspx
This should do the trick:
I think your trying to mix server side and client side events here.
The html attribute
OnClick
is a client side, when a user clicks on the button it fires a piece of JavaScript The server eventOnClick
happens when a user clicks a button and it posts back to the server, which allows you to hook functions (server side) into that event.Are you looking for server side or client side?
To add a client side event you can do
To add a server side event you can do
Where this.MyMethod is a method already seutp to handle the server side button click.
If I were right, you create buttons in
Page_Load
.If it is check for postbacks.
read the article about the asp.net webforms life-cycle http://msdn.microsoft.com/en-us/library/ms178472.aspx. you have to create/recreate your controls everytime when loading the page (e.g. OnLoad-Method)
http://www.asp.net/web-forms/videos/aspnet-ajax/how-to-dynamically-add-controls-to-a-web-page