Gridview Rowcommand Datakey使索引超出范围错误

时间:2012-03-04 20:58:27

标签: c# asp.net gridview rowcommand datakey

我在gridview中添加了一个名为reserve的按钮,当我点击它时,我想对gridview进行一些修改,但是它会使索引超出范围错误。下面是rowCommand方法:

    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();
        }            
    }

以下是我的gridview专栏:

        <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>

1 个答案:

答案 0 :(得分:1)

如果您希望使用DataKey [index]表达式,则需要设置DataKeyNames See MSDN here