Tuesday, January 10, 2012

Adding Javascript OnClick to ASP.NET Grid View Edit Button

Recently, I had a need to add a javascript onclick event to the edit LinkButton that a GridView display when you set the CommandField and ShowEdit to True.

<asp:CommandField ShowEditButton="True" />

This solution will actually work for any control automagically added by ASP.NET with the CommandField options.

The trick is, it loops through all the rows in the underlying table created by the GridView, examines the cells in those rows for controls, locates the control you are looking for, and then, it can access the attributes of that control.

You will have to be careful here because as you can see from the solutions, it's using the prior knowledge that the only LinkButton in any of the cells is the one we want to access.  If you have more controls, you will need to be a bit more clever about locating the control.  For example, you could specify WHICH cell in the cell array by index or which control in the control array if your LinkButton is always in the same position.


                For Each r As TableRow In Grid.Rows
                    For Each a As TableCell In r.Cells
                        If a.Controls.Count > 0 AndAlso TypeOf a.Controls(0) Is LinkButton Then
                            CType(a.Controls(0), LinkButton).Attributes.Add("onclick", "NoCheck();")
                        End If
                    Next
                Next

No comments:

Post a Comment