Saturday, January 23, 2010

Container.DataItemIndex - Getting GridView's Row Index

Every once in a while you need to get the index of the row in a GridView that triggered an event. You can setup the CommandArgument to store the row’s index for use in your code behind. In the GridView:
<asp:GridView ID="gridView" runat="server" DataKeyNames="myId" OnRowCommand=" gridView_RowCommand">
    <Columns>
        <asp:TemplateField ShowHeader="False">
            <ItemTemplate>
                <asp:Button ID="btnAdd" runat="server" CommandArgument='<%# Container.DataItemIndex %>'
                    CommandName="Add" Text="Add" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
Referencing in the code-behind:
protected void gridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Add")
    {
        int myId = (int)gridView.DataKeys[Convert.ToInt32(e.CommandArgument)].Value;
    }
}