C# 在GridView上添加行会得到;指定的参数超出了有效值的范围;

C# 在GridView上添加行会得到;指定的参数超出了有效值的范围;,c#,asp.net,gridview,C#,Asp.net,Gridview,我试图根据某些条件在GridVIew上添加一些行,并得到“指定的参数超出了有效值的范围”错误。 这是我的GridView: <asp:GridView ID="gvConcept" runat="server" CellPadding="0" CssClass="table" CellSpacing="0" AutoGenerateColumns="false" GridLines="Vertical" BorderStyle="Solid" ShowFooter="false" OnRo

我试图根据某些条件在GridVIew上添加一些行,并得到“指定的参数超出了有效值的范围”错误。 这是我的GridView:

<asp:GridView ID="gvConcept" runat="server" CellPadding="0" CssClass="table" CellSpacing="0" AutoGenerateColumns="false" GridLines="Vertical" BorderStyle="Solid" ShowFooter="false" OnRowDataBound="gvConcept_RowDataBound" OnRowCreated="gvConcept_RowCreated" >
        <Columns>
            <asp:BoundField DataField="Concept" HeaderText="  Concept" />
            <asp:BoundField DataField="Client" HeaderText="  Client" />
            <asp:BoundField DataField="YTD" HeaderText="  YTD" ItemStyle-HorizontalAlign="Right" />
        </Columns>
    </asp:GridView>
第一行添加正确,但下一行(在我的案例2中)无法添加。
有什么意见吗?谢谢。

我认为您应该使用1作为最后一个参数调用AddNewRow函数,而不是e.RowIndex+1。在第一次调用时,它将以值(0+1)的形式传递1,但在第二次调用时,它将传递2(1+1),并且将为索引3调用InsertAt AddAt:e.Row.RowIndex+2=3

您是否已使用debug检查了e.Row.RowIndex和第二次调用时的RowIndex是什么?
e.Row.RowIndex+1
可以替换为
e.Row.RowIndex
,只需按照建议更改代码即可。第一个添加的行,在正确的位置。第二行,在前面添加了1行,第三行在前面添加了2行。请为手动添加的行数创建一个计数器。把你的指数提高那么多。所以,对于要添加0的第一行、第二行1和第三行2,依此类推。。。虽然有点奇怪。。。最好检查AddAt上的索引。只需在AddNewRow上放置一个计数器,但尽管它只添加了3行,但计数器将变为17。不确定如何增加它,但每次添加新行时,只需将计数器增加1。
string ParAnt = string.Empty;
string partner = string.Empty;
protected void gvConcept_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ParAnt = DataBinder.Eval(e.Row.DataItem, "Partner").ToString();
    }
}

public void AddNewRow(object sender, GridViewRowEventArgs e, int rowIndex)
{
    GridView GridView1 = (GridView)sender;
    GridViewRow NewTotalRow = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert);
    NewTotalRow.Font.Bold = true;
    NewTotalRow.ForeColor = System.Drawing.Color.Black;
    NewTotalRow.BackColor = System.Drawing.Color.LightGray;
    TableCell HeaderCell = new TableCell();
    HeaderCell.Height = 10;
    HeaderCell.HorizontalAlign = HorizontalAlign.Left;
    HeaderCell.ColumnSpan = 4;
    HeaderCell.Text = partner;
    NewTotalRow.Cells.Add(HeaderCell);
    GridView1.Controls[0].Controls.AddAt(e.Row.RowIndex + rowIndex, NewTotalRow);
}

protected void gvConcept_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        partner = DataBinder.Eval(e.Row.DataItem, "Partner").ToString();
        if (ParAnt != partner)
        {
            AddNewRow(sender, e, e.Row.RowIndex+1);
            ParAnt = DataBinder.Eval(e.Row.DataItem, "Partner").ToString();
        }
    }
}