James Balentine James Balentine - 1 year ago 123
ASP.NET (C#) Question

Get a reference to the edit button in a gridview with FindControl

My question is: What is the ID of an Edit button defined as a CommandField in a GridView? I want to be able to reference this button using the FindControl method in the code-behind, but, since I don't know the Edit button's ID, I can't. I have to reference it by index.

This is the detail of what I'm trying to do:

I have an ASP.NET 4.5.1 GridView control with an edit button and a delete button. They are defined as follows:



<asp:CommandField ShowEditButton="true" UpdateText="Save" ShowDeleteButton="false" ValidationGroup="vgParcelComments" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnDeleteParcelComment" runat="server" OnClientClick="return confirm('Are you sure that you want to delete this comment?');" CommandName="Delete" CssClass="removeParcelComment">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>





In the RowDataBound event for this GridView in my code-behind page, I can manipulate the Delete button with the following line of code:

e.Row.FindControl("btnDeleteParcelComment").Visible = False 'The delete button


This hides the Delete button. But, for the Edit button, I can't determine what its ID is, so I can't use the FindControl function to access it. The best that I can do is reference it by index, like so:

e.Row.Cells(4).Visible = False 'The edit button


I tried to look at the Edit button's ID using the following statement:

Dim itsId As String = e.Row.Cells(4).ID


but Nothing was always returned when this line executed.

Tak.

Answer Source

You can look in the Controls collection of the cell for the LinkButton which has Edit as its CommandName:

Dim editButton As LinkButton = Nothing
For Each cell As DataControlFieldCell In e.Row.Cells
    For Each ctl As Control In cell.Controls
        If TypeOf ctl Is LinkButton Then
            Dim commandButton As LinkButton = CType(ctl, LinkButton)
            If commandButton.CommandName = "Edit" Then
                editButton = commandButton
                Exit For
            End If
        End If
    Next
Next