views:

20

answers:

1

Hi All,

I've created some code that will dynamically generate a bunch of different LinkButtons. I've got each link button's onClick even pointing to:

  void LinkButton_Click(object sender, EventArgs e) 
  {
     Response.Write("You clicked the link button");
  }

This runs fine, but now I when one of the LinkButtons is click I want to get its ID and send that to another function.

Any help would be greatly appreciated.

Matt

+3  A: 

You need to cast sender to the specific type of control, as in:

void LinkButton_Click(Object sender, EventArgs e) 
{
  LinkButton button = sender as LinkButton;

  if(button != null)
  {
    //do something
  }

  Response.Write("You clicked the link button";  
}

The as operator will attempt to cast sender to type LinkButton. If this is not successful, local variable button will be set to null. Note that this is different behavior than (LinkButton)sender, which will throw an exception if the typecast is not appropriate.

David Andres
fantastic, thanks mate. I was playing around with (LinkButton)sender earlier!
bExplosion
bExplosion: good deal. Just to add to the discussion, you can cast sender to WebControl as well. This is helpful if you intend for this event to be fired by more than an single type of server control. For this to work, all of the controls will need to extend from WebControl (which most do anyway).
David Andres