Search code examples
c#asp.net.netlinkbutton

LinkButton.OnClick Method with Parameter


I'm creating a linkButton Dynamically on ASP.net. I need help on when I click the linkButton, it will store the linkbutton name to my Label1 (for example only).

Here is the code:

protected void Page_Load(object sender, EventArgs e)
    {
        for (int ctr = 0; ctr <= 2; ctr++)
        {
            LinkButton link = new LinkButton();
            link.ID = "lnk" + ctr.ToString();
            link.Text = "lnkName" + ctr.ToString();
            link.Click += new EventHandler(DynamicClick);
            this.form1.Controls.Add(link);
        }
    }

//when I click the buttonLink
public void DynamicClick(object sender, EventArgs e)
    {
        //label1.text will get the .text of the button that i pressed
        Label1.Text = "";
    }

Solution

  • I would do it in that way

    public void DynamicClick(object sender, EventArgs e)
    {
        LinkButton linkButton = sender as LinkButton;
        if (linkButton != null)
        {
            Label1.Text = linkButton.Text;
        }
    }