2016-02-12 48 views
2

我想基于某些条件在GridVIew上添加一些行,并且我得到“指定的参数超出范围有效值“错误。 这是我的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> 

这是我的代码隐藏:

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

第一行正确添加,但不能添加的下一个的人(在我的情况2)。 任何人输入?谢谢。

+0

你检查过使用调试,什么是e.Row.RowIndex和rowIndex第二次调用? –

+0

'e.Row.RowIndex + 1'可以替换为'e.Row.RowIndex' –

回答

1

我相信你应该用1作为最后一个参数来调用你的AddNewRow函数,而不是e.RowRowIndex + 1.在第一次调用时,这会传递1作为值(0 + 1),但第二次传递2 1 + 1)和InsertAt AddAt将被称为索引3:e.Row.RowIndex + 2 = 3.

+0

只需按照建议更改代码即可。首先在正确的位置添加行。第二行,之前添加1行,第三行之前添加2行。 –

+0

为您手动添加多少行创建一个计数器。提高你的指数。因此,对于第一行,您将添加0,对于第二个,对于第三个,等等......虽然它有点奇怪......最好在AddAt上检查您的索引。 –

+0

只是在AddNewRow上放置了一个计数器,但尽管它只增加了3行,计数器也会减少到17个。 –