Innova
Innova

Reputation: 4971

How to get link button id that is generated dynamically from code behind in the event handler

I have created two link buttons dynamically:

for (int i = 0; i < 2; i++) {
    LinkButton lb = new LinkButton();
    lb.ID = "lnk" + FileName;
    lb.Text = FileName;
    Session["file"] = FileName;
    lb.CommandArgument = FileName;
    lb.Click += new EventHandler(Lb_Click);
    Panel1.Controls.Add(lb);
    Panel1.Controls.Add(new LiteralControl("<br />"));
}

I have got two links, namely:

  1. File11
  2. File22

And I need to determine which one was clicked:

void Lb_Click(object sender, EventArgs e) {
    string id=lb.ID;

    //Here - how to get link button id which is clicked (either File11 id or File22 id)?
}

Upvotes: 1

Views: 8895

Answers (2)

XYZ
XYZ

Reputation: 27387

You acturally do not need to generate an ID for your dynamicly generated buttons. Because when the button OR Link get clicked, the event handler not only received the event itself but also the sender information as well.

String buttonText = (LinkButton)sender.Text;

Multiple buttons can share the same event-handler, and perform the corresponding task for differnet button clicked based on the different name.

Upvotes: 0

David Neale
David Neale

Reputation: 17028

In your event handler:

LinkButton clickedButton = (LinkButton)sender;

You could then access the ID using clickedButton.ID

Here's an MSDN walkthrough: http://msdn.microsoft.com/en-us/library/aa457091.aspx for determining senders of events.

Upvotes: 5

Related Questions