Nuno Ramos
Nuno Ramos

Reputation: 49

Adding Row on GridView gets "Specified argument was out of the range of valid values"

I'm trying to add some rows on a GridVIew based on some condition, and I'm getting the "Specified argument was out of the range of valid values" error. This is my 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>

this is my codebehind:

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

The first row is added correctly, but the next ones (on my case 2) can't be added. Any input anyone? Thanks.

Upvotes: 2

Views: 378

Answers (1)

Nemanja Todorovic
Nemanja Todorovic

Reputation: 2840

I beleive that you should call your AddNewRow function with 1 as last parameter, instead e.RowRowIndex + 1. On first call this will pass 1 as value (0 + 1), but on second one it will pass 2 (1 + 1) and InsertAt AddAt will be called for index 3: e.Row.RowIndex + 2 = 3.

Upvotes: 1

Related Questions