Home > DeveloperSection > Forums > Why link button does not fire click event on first time click when add dynamicly?
ezra heywood
ezra heywood

Total Post:145

Points:1019
Posted on    October-06-2014 12:09 AM

 C# ASP.Net  C# 
Ratings:


 1 Reply(s)
 629  View(s)
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?



Kamlakar Singh
Kamlakar Singh

Total Post:194

Points:1396
Posted on    October-06-2014 12:10 AM

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);

            }

        }

Don't want to miss updates? Please click the below button!

Follow MindStick