开发者

How to dynamically add a runat server button in asp.net

开发者 https://www.devze.com 2023-03-26 03:47 出处:网络
Actually, I want to know how to add it\'s click event. Button b = new Button(); b.Text = \"Go back!\"; b.ID = \"btn_Back\";

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号