0

I have added a button named reserve to my gridview, and when I click it I want do some modification on the gridview, however it gives index out of range error. Below is rowCommand method:

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int index = Convert.ToInt32(e.CommandArgument);
        GridViewRow row = GridView1.Rows[index];

        if (row.RowType == DataControlRowType.DataRow)
        {
            welcomeUser.InnerText = GridView1.DataKeys[index].Value.ToString();
        }            
    }

Below is my gridview columns:

        <Columns>
            <asp:BoundField DataField="Id" HeaderText="Id" SortExpression="Id" />
            <asp:BoundField DataField="BookName" HeaderText="BookName" 
                SortExpression="BookName" />
              <asp:ButtonField ButtonType="Button" Text="Reserve" CommandName="Reverse" />
        </Columns>
HOY
  • 1,067
  • 10
  • 42
  • 85
  • 3
    Do you set DataKeyNames on your gridview? – Steve Mar 04 '12 at 21:25
  • this solved the problem, please write it as an answer and I will accept it, do I need datakeys to make modifications on the data? – HOY Mar 05 '12 at 17:08

1 Answers1

1

You need to set the DataKeyNames if you wish to use DataKey[index] expression
See MSDN here

Steve
  • 213,761
  • 22
  • 232
  • 286