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);
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
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 event OnClick
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
btn2.Attributes.Add("onclick","my_javascript_function");
To add a server side event you can do
btn2.Click += new System.EventHandler(this.MyMethod);
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.
if(!postback)
{
create your buttons.
}
Create a method for adding all Your dynamical controls as below
public void AddControls()
{
Button btn2 = new Button();
btn2.ID = "btnEdit";
btn2.Text = "Edit Member";
btn2.Click += new EventHandler(btnEdit_Click);
form1.Controls.Add(btn2);
}
and then call that method in Page_Load() Event & out side of the IsPostBack block as below
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
AddControls();
}
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:
protected void Page_Load(object sender, EventArgs e)
{
Button b = new Button() { ID = "btnEdit", Text = "Edit Member" };
b.Click += (sd, ev) => {
// Do whatever you want to be done on click here.
Button me = (Button)sd; // This creates a self-reference to this button, so you can get info like button ID, caption... and use, like this:
me.Text = "Yay! You clicked me!";
};
form1.Controls.Add(b);
}