How to dynamically add a runat server button in asp.net
Actually, I want to know how to add it's click event.
Button b = new Button();
b.Text = "Go back!";
b.ID = "btn_Back";
b.Click 开发者_开发百科= ??
b.Click += new EventHandler(btn_Click);
and then declare btn_Click, like:
void btn_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
If you're in VS2005 versions, once you hit b.Click += you'll be queried to hit TAB and declare it all automatically!
Kind regards, Henrik.
Here is how to register the event handler (using the +=
notation):
b.Click += new EventHandler(NameOfHandler);
You will need a function called NameOfHandler
that corresponds to the EventHandler
delegate - that is, that takes a first parameter of type object
and a second paremeter of type EventArgs
:
public void NameOfHandler(object o, EventArgs e)
{
// code here
}
Normally, in visual studio once you have typed the +=
following the event name, tabbing a couple of times will generate the rest of the line and an empty event handler function.
Button b = new Button();
b.Text = "Go back!";
b.ID = "btn_Back";
b.Click += new EventHandler(B_Click);
Controls.Add(b);
// ...
private void B_Click(object sender, EventArgs e)
{
// ...
}
精彩评论