Search code examples
c#asp.netgridviewrowcommand

Find Gridview ID from within its RowCommand event


I have three GridViews whose IDs are: grdvwFilteredNo1, grdvwFilteredNo2, grdvwFilteredNo3

each with its own RowCommand event (each fired off by a LinkButton, on a row)

grdvwFilteredNo1_RowCommand(object sender, GridViewCommandEventArgs e) grdvwFilteredNo2_RowCommand(object sender, GridViewCommandEventArgs e) grdvwFilteredNo3_RowCommand(object sender, GridViewCommandEventArgs e)

I'm looking to consolidate code by having all three Gridviews call the same RowCommand event. (The event code for all three is the same, except for this line where I identify the gridview by it's ID.
Here's the line from the first event;
Int32 intSelectedEEid = (Int32)grdvwFilteredNo1.DataKeys[rowIndex].Values["EmployeeID"];)

I was thinking I could use a variable instead of the gridview ID, but I can't seem to grab the gridview ID. Using this
GridView gView = ((Control)e.CommandSource).Parent.Parent as GridView;
gView.ID comes back null.

I was thinking the parent of the LinkBtn was the row and the parent of the row was the gridview.

How do I find the gridview id from within its RowCommand event? Thanks for the help.


Solution

  • To reach the GridView from the RowCommand event you should use something like this

    GridViewRow row = ((e.CommandSource as LinkButton).NamingContainer) as GridViewRow;
    GridView grd = row.NamingContainer as GridView;
    

    Using Parent doesn't work because the parent of your LinkButton is probably not directly the GridViewRow but its ItemTemplate, instead the NamingContainer will walk the chain of the ancestors until it finds one that implements the INamingContainer interface.