简体   繁体   中英

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)
{
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM