开发者

Setting LinkButton's OnClick event to method in codebehind

开发者 https://www.devze.com 2023-01-22 13:33 出处:网络
I\'m constructing a LinkButton from my codebehind, and I need to assign the onclick to a method, and pass a parameter with it too. I have this so far:

I'm constructing a LinkButton from my codebehind, and I need to assign the onclick to a method, and pass a parameter with it too. I have this so far:

LinkButton lnkdel = new Li开发者_JAVA百科nkButton();
lnkdel.Text = "Delete";

The method I want to pass it to looks like this:

 protected void delline(string id)
        {

        }


Well you can't pass it to that method, you need to assign the click event delegate to a method capable of handling it.

Like this:

public void DynamicClick(object sender, EventArgs e) {
    // do something
}

Assign the click event like any event:

lnkdel.Click += new EventHandler(DynamicClick);

If you want to pass an argument, use CommandArgument, and you'll need a different delegate:

void DynamicCommand(Object sender, CommandEventArgs e) 
      {
         Label1.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
      }

And then:

lnkDel.Command += new CommandEventHandler(DynamicCommand)
lnkDel.CommandArgument = 1234;

BTW if you're on >= C#3, you can also use the coolness of anonymous methods:

lnkDel.Command += (s, e) => { 
   Label1.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
};


The function prototype for this event is:

protected void lnkdel_OnClick(object _sender, EventArgs _args)
{
    LinkButton src = (LinkButton)_sender;
    // do something here...
}

Assign it with:

LinkButton lnkdel = new LinkButton();
lnkdel.Text = "Delete";
lnkdel.OnClick += new EventHandler(lnkdel_OnClick);
0

精彩评论

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

关注公众号