WHY LINK BUTTON DOES NOT FIRE CLICK EVENT ON FIRST TIME CLICK WHEN ADD DYNAMICLY?

ezra heywood

Total Post:145

Points:1019
Posted by  ezra heywood
ASP.Net  C# 
C#
 974  View(s)
Ratings:
Rate this:
I am dynamically adding Link Buttons to my Gridview as seen below:

protected void addLinks()

        {

            foreach (GridViewRow gvr in gvData.Rows)

            {

                if (gvr.RowType == DataControlRowType.DataRow)

                {

                    string itemNbr = gvr.Cells[1].Text;

                    LinkButton lb = new LinkButton();

                    lb.Text = itemNbr;

                    lb.Click += genericLinkButton_Click;

                    foreach (Control ctrl in gvr.Cells[1].Controls)

                    {

                        gvr.Cells[1].Controls.Remove(ctrl);

                    }

                    gvr.Cells[1].Controls.Add(lb);

                }

            }

        }

This addLinks() function is called in my gridview_RowDataBound event and the Page Load event if(isPostPack).

The problem is that when I click the link buttons, the genericLinkButton_Click event does not get fired on my first click. It causes a postback, and then if I click it again, or click one of the other Link Buttons, the genericLinkButton_Click event is fired.

How can I make sure the click event happens on my first click?

  1. Kamlakar Singh

    Post:194

    Points:1396
    Re: Why link button does not fire click event on first time click when add dynamicly?

    When using Webforms and dynamically creating controls you are required to assign an ID to the created control before adding the control to the tree in order for them to work properly. Otherwise they will have changing ID's during the pagelifecycle resulting in the described behaviour.

    private int _runningIndex = 0;

            protected void gvData_RowCreated(Object sender, GridViewRowEventArgs e)

            {

                if (e.Row.RowType == DataControlRowType.DataRow)

                {

                    string itemNbr = e.Row.Cells[1].Text;

                    LinkButton lb = new LinkButton();

                    lb.ID = "btn" + (_runningIndex++).ToString();

                    lb.Text = itemNbr;

                    lb.Click += genericLinkButton_Click;

                    foreach (Control ctrl in e.Row.Cells[1].Controls)

                    {

                        e.Row.Cells[1].Controls.Remove(ctrl);

                    }

                    e.Row.Cells[1].Controls.Add(lb);

                }

            }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!