In this article I will explain how to set Row Index of the GridView Row to CommandArgument property of Button control. The following works for C# but does not work for VB.Net. I will explain a easier way which works in both C# and VB.Net.
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
 
 
HTML Markup
The following HTML Markup consists of an ASP.Net GridView with three BoundField columns and a TemplateField column containing a Button whose CommandArgument property is bound to Container.DataItemIndex property.
The Container.DataItemIndex is the index of the data item bound to the GridView and it can be used to determine the Row Index of the GridView Row.
<asp:GridView ID="GridView1" runat = "server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Customer Id" ItemStyle-Width="100px" />
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="120px" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="120px" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button Text="Select" runat="server" OnClick="Select" CommandArgument='<%# Container.DataItemIndex %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
 
 
Namespaces
You will need to import the following namespace.
Imports System.Data
 
 
Binding the ASP.Net GridView control
I have created a dynamic DataTable with some dummy data and it is used to populate the GridView control in the Page Load event.
Note: You can learn more about this dynamic DataTable in my article Create DataTable dynamically and bind to GridView in ASP.Net.
 
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id"), New DataColumn("Name"), New DataColumn("Country")})
        dt.Rows.Add(1, "John Hammond", "United States")
        dt.Rows.Add(2, "Mudassar Khan", "India")
        dt.Rows.Add(3, "Suzanne Mathews", "France")
        dt.Rows.Add(4, "Robert Schidner", "Russia")
        GridView1.DataSource = dt
        GridView1.DataBind()
    End If
End Sub
 
 
Fetching the value of GridView Row Index from CommandArgument in Button Click event handler
When the Button is clicked, the value of the GridView Row Index is fetched from the CommandArgument property and displayed using JavaScript Alert message box.
Protected Sub [Select](sender As Object, e As EventArgs)
    Dim rowIndex As String = TryCast(sender, Button).CommandArgument
    ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", "alert('Row Index: " & rowIndex & "');", True)
End Sub
 
 
Screenshot
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
 
 
Demo
 
 
Downloads