Accessing Non-Public Members of the GridViewCommandEventArgs Object
I have a gridview in my aspx page to set up an OnRowCommand event using a series of ASP.NET LinkButton objects to handle the logic using the CommandName property. I need to access the GridViewRow.RowIndex to retrieve values from the selected row and notice that these are non-public members of the GridViewCommandEventArgs object when debugging the application
Is there a better way I can access this property?
Here's my source code:
The aspx page:
<asp:GridView ID="MyGridView" runat="server" OnRowCommand="MyGirdView_OnRowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton
id="MyLinkButton"
runat="server"
CommandName="MyCommand"
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code for
protected void MyGirdView_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
//need to access row index here....
}
UPDATE:
@brendan - I got the following compilation error on the following line of code:
"Unable to convert type 'System.Web.UI.WebControls.GridViewCommandEventArgs' to 'System.Web.UI.WebControls.LinkButton'"
LinkButton lb = (LinkButton) ((GridViewCommandEventArgs)e.CommandSource);
I changed the code a bit and the following solution worked:
LinkButton lb = e.CommandSource as LinkButton;
GridViewRow gvr = lb.Parent.Parent as GridViewRow;
int gvr = gvr.RowIndex;
source to share
Not the cleanest thing in the world, but this is how I've done it in the past. I usually do everything on one line, but I'll break it down here to make it clearer.
LinkButton lb = (LinkButton) ((GridViewCommandEventArgs)e.CommandSource);
GridViewRow gr = (GridViewRow) lb.Parent.Parent;
var id = gr.RowIndex;
Basically you get your button and move the chain from button to cell, from cell to row.
Here is a one line version:
var id = ((GridViewRow)((LinkButton)((GridViewCommandEventArgs)e).CommandSource).Parent.Parent).RowIndex;
source to share