1
votes

So.. I'm dynamically creating LinkButtons on my page like this:

LinkButton lb = new LinkButton();
lb.Click += new EventHandler(lb_Click);

When one of these LinkButtons is clicked, I need to know which one the links was clicked, then create another LinkButton and attach an onclick event on it. (How) can I do this? If I have understood correctly, click events can't be attached in (this case in) lb_Click function, so is there any way I still could do this?

Edited:

To make this problem more understandable, here's how I tried to make it but it does not work:

LinkButton lb = new LinkButton();
lb.click += new EventHandler(lb_Click);

void lb_Click(object sender, EventArgs e)
{
    LinkButton lb2 = new LinkButton();
    lb2.click += new EventHandler(lb2_Click);
}

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

Clicking lb2 does not fire the lb2_Click event.

2
set unique id for each link button and check that in link button event handler. - pmtamal
Did you not read what I wrote? If I create new LinkButton in lb_Click and try add new eventhandler on it, clicking the LinkButton won't launch the event. Or am I doing it wrong? - ville_j
How did you add the link buttons to the page? - Tariqulazam
For example: tc4.Controls.Add(lb); (tc4 is a table cell element on the page) - ville_j

2 Answers

0
votes

You can try with this code - based on sender argument

LinkButton lb = new LinkButton();
lb.Id= "Test1";
lb.Click += new EventHandler(lb_Click);

LinkButton lb2 = new LinkButton();
lb2.Id= "Test2";
lb2.Click += new EventHandler(lb_Click);

void LinkButton_Click(Object sender, EventArgs e) 
{
   var yourControl = (LinkButton)sender;
   var id = yourControl.Id;
   if(id == "Test1")
   {
      ...
   }
   else if(id == "Test2")
   {
      ...
   }

}
0
votes

Yes, yes, yes: I'm very, very late to the party.
BUT for future reference of anyone coming to this post:

Your methods are marked as private (omitting an access modifier defaults to private), which means they are not accessible enough for them to be called.

Instead, use the protected modifier to ensure they get called properly.

Like so:

LinkButton lb = new LinkButton();
lb.click += new EventHandler(lb_Click);

protected void lb_Click(object sender, EventArgs e)
{
    LinkButton lb2 = new LinkButton();
    lb2.click += new EventHandler(lb2_Click);
}

protected void lb2_Click(object sender, EventArgs e)
{
    //do something
}

Hope this helps some future visitors :)