views:

910

answers:

1

I have a gridview on my aspx page set up the OnRowCommand event using a series of ASP.NET LinkButton object to handle the logic using the CommandName property. I need to access the GridViewRow.RowIndex to retrieve values from the selected row and notice it is a non-public members of the GridViewCommandEventArgs object while debugging the application

Is there a way I can access this property of is theere a better implementation?

Here is my source code:

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 behind

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:

"Cannot convert type 'System.Web.UI.WebControls.GridViewCommandEventArgs' to 'System.Web.UI.WebControls.LinkButton'"

LinkButton lb = (LinkButton) ((GridViewCommandEventArgs)e.CommandSource);

I slightly modified the code and the following solution worked:

LinkButton lb = e.CommandSource as LinkButton;
GridViewRow gvr = lb.Parent.Parent as GridViewRow;
int gvr = gvr.RowIndex;
+1  A: 

Not the cleanest thing in the world but this is how I've done it in the past. Usually I'll make it all one line but I'll break it down here so it's more clear.

LinkButton lb = (LinkButton) ((GridViewCommandEventArgs)e.CommandSource);
GridViewRow gr = (GridViewRow) lb.Parent.Parent;
var id = gr.RowIndex;

Basically you get your button and move up the chain from button to cell, from cell to row.

Here is the one row version:

   var id = ((GridViewRow)((LinkButton)((GridViewCommandEventArgs)e).CommandSource).Parent.Parent).RowIndex;
brendan
I provided a follow up to your answer
Michael Kniskern
Actually, this is rather clean way to handle this. I don't use gridviews often, but when I do, I grab all the info out of the calling control.
Wyatt Barnett