GridView Find Control by Name on RowCommand

Posted: October 5, 2010 in ASP.Net

If you need to get the value of a control in a GridView when a button is clicked on the row for example, you can try the following:
ASP.Net (Desgin)
Place a GridView control and the following template fields. The clicking of the lbtn_product_code link button is what we are going to use to find the value of the label lbl_product_id.

<asp:GridView id="grd_product" runat="server" OnRowCommand="p_RowCommand">
        <asp:TemplateField HeaderText="Product Code">
                <asp:LinkButton ID="lbtn_product_code" runat="server" CommandArgument='<%#Eval("product_code") %>' CommandName="Select"></asp:LinkButton>
        <asp:TemplateField Visible="False">
                <asp:Label ID="lbl_product_id" runat="server" Text='<%# Eval("product_id") %>'></asp:Label>

ASP.Net (Code Behind)
Now add some code around the RowCommand event as follows:

' Routine for when a row command is initiated
Protected Sub p_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
   If e.CommandName = "Select" Then
      Dim lbl_product_id As Label
      Dim lgvr_current_row As GridViewRow = DirectCast(DirectCast(e.CommandSource, LinkButton).Parent.Parent, GridViewRow)
      lbl_product_id = grd_product.Rows(lgvr_current_row.RowIndex).FindControl("lbl_product_id")
      If e.CommandArgument = "<product code>" Then
         ' Do something
      End If
   End If
End Sub

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s