Krishna shidnekoppa
Krishna shidnekoppa

Reputation: 1059

How to find label control in the RowCommand method of grid view?

GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lblUser = clickedRow.FindControl("lblFullName") as Label;
Label lblUserId = (Label)clickedRow.FindControl("lblUserId");

Compiler throwing error as

Unable to cast object of type 'System.Web.UI.WebControls.GridView'

Upvotes: 2

Views: 3576

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21795

The problem with your current code is that the GridView's RowCommand event is raised by gridview itself and not by an individual control thus your cast will fail:-

(LinkButton)sender

Because sender here is Gridview and not linkbutton.

Now, you may have multiple controls in your gridview which can raise this event(or you may add them in future) so add a CommandName attribute to your LinkButton like this:-

<asp:LinkButton ID="myLinkButton" runat="server" Text="Status" 
     CommandName="myLinkButton"></asp:LinkButton>

Finally in the RowCommand event you can first check if the event is raised by the LinkButton and then safely use the e.CommandSource property which will be a LinkButton and from there find the containing row of Gridview.

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
   if (e.CommandName == "myLinkButton")
   {
      LinkButton lnk = (e.CommandSource) as LinkButton;
      GridViewRow clickedRow = lnk.NamingContainer as GridViewRow;
   }
}

Upvotes: 5

Related Questions