C# – Get GridView Row

asp.netcgridview

I have a GridView which I bind to a SqlDataReader on Page_Load. It has a column with buttons and I am trying to get the row when a button is clicked with the following code:

int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];

EDIT : Pasting the .aspx page from the comments sectio

 <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" OnRowCommand="GridView1_RowCommand" DataKeyNames="id" GridLines="None"> <AlternatingRowStyle BackColor="White" /> 
    <Columns> 
        <asp:TemplateField> 
             <ItemTemplate> 
                  <asp:Button ID="btnChange" runat="server" Text="Change" CommandName="Test" Visible='<%# Convert.ToBoolean(Eval("Tested")) == true ? true : false %>' /> 
             </ItemTemplate> 
         </asp:TemplateField> 
     </Columns>
</aspx:GridView> 

I get the following error: 'System.FormatException: Input string was not in a correct format.' on line 'int index = Convert.ToInt32(e.CommandArgument);'.

Any ideas?

Best Answer

You need to check which command in the GridView row has been clicked. Your markup should correspondingly map. See egs below. The e.CommandArgument you are getting may not correspond to your button click.

In CodeBehind:

    void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
    {
    // If multiple buttons are used in a GridView control, use the CommandName property to determine which button was clicked.
    if(e.CommandName=="Add")
    {
    // Convert the row index stored in the CommandArgument property to an Integer.
    int index = Convert.ToInt32(e.CommandArgument);

    // Retrieve the row that contains the button clicked by the user from the Rows collection.
    GridViewRow row = CustomersGridView.Rows[index];

    // additional logic...
    }
    // additional logic...
}

In Markup:

Also please ensure you have set your CommandArgument attribute appropriately. Example below:

<asp:Button (...) CommandArgument="<%# Container.DataItemIndex %>" />

OR use a buttonfield

<asp:ButtonField ButtonType="button" CommandName="Add" Text="Add" />