views:

49

answers:

2

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 LinkButton();
lnkdel.Text = "Delete";

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

 protected void delline(string id)
        {

        }
A: 

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);
Moo-Juice
+1  A: 

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;
};
RPM1984
Thanks buddy, I'm trying to use the second method you posted as the purpose is the post is to pass an ID through for deletion. .OnCommand didn't appear in the intellisense list, and when I try to type it anyway it tells me that the LinkButton is inacessible due to its protection level?
Chris
@Chris - yes, forgot about that 'bug/feature' with linkbutton. try this: `lnkDel.Command += new CommandEventHandler(DynamicCommand)` or just `lnkDel.Command += DynamicCommand`.
RPM1984
Thanks buddy, it compiles but it doesn't seem to ever go into the Command - am I missing something? I've tried the C#3 method as well, which compiles but again never goes into that method
Chris
There are a wealth of issues with dynamically created controls. Here's what i suggest, first add a regular linkbutton to the page (non dynamic, add it to the ASPX/ASCX), and set the command from the code-behind like above (don't new up the button, just set the command/commandargument). See if it works. It should, and if it does, it means you're probably missing something with dynamic controls - like not re-creating the controls on postback, etc.
RPM1984
Keep in mind - dynamically created controls need to be re-created on postback (in the Page_Load event). Are you doing that? If you cant set the commandargument in Page_Load for whatever reason, you'll need to store the commandargument(s) in viewstate. This kind of thing can get quite messy.
RPM1984