[c#] "Specified argument was out of the range of valid values"

I'm adding dynamic Rows in ASP.Net GridView Control with TextBoxes. But I'm getting the error below when I click on my Add New Row button.

Specified argument was out of the range of valid values. Parameter name: index

What could be the error ?

Th code in my .aspx file

<div id="Div1" class="divTable">
    <asp:gridview id="Gridview1" runat="server" autogeneratecolumns="false" gridlines="None"
        width="100%" height="100%">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <div class="divRow">
                            <div class="divColumn">
                                <div>
                                    <asp:Label ID="lbl1" runat="server" Text="Type Name" CssClass="formLable"></asp:Label>
                                </div>
                                <div>
                                    <asp:TextBox ID="txt_type" Width="200" runat="server" CssClass="txtbox"></asp:TextBox>
                                </div>
                                <span>
                                    <asp:RequiredFieldValidator ID="TYPE_NAME_VAL" runat="server" ControlToValidate="txt_type"
                                        ErrorMessage="Type is required." Display="Dynamic" CssClass="error"></asp:RequiredFieldValidator>
                                </span>
                            </div>
                            <div class="divColumn">
                                <div>
                                    <asp:Label ID="lbl2" runat="server" Text="Total" CssClass="formLable"></asp:Label>
                                </div>
                                <div>
                                    <asp:TextBox ID="txt_total" Width="200" runat="server" CssClass="txtbox"></asp:TextBox>
                                </div>
                            </div>
                        </div>
                        <div class="divRow">
                            <div class="divColumn">
                                <div>
                                    <asp:Label ID="lbl3" runat="server" Text="Max" CssClass="formLable"></asp:Label>
                                </div>
                                <div>
                                    <asp:TextBox ID="txt_max" Width="200" runat="server" CssClass="txtbox"></asp:TextBox>
                                </div>
                            </div>
                            <div class="divColumn">
                                <div>
                                    <asp:Label ID="lbl4" runat="server" Text="Min" CssClass="formLable"></asp:Label>
                                </div>
                                <div>
                                    <asp:TextBox ID="txt_min" Width="200" runat="server" CssClass="txtbox"></asp:TextBox>
                                </div>
                            </div>
                            <div class="divColumn">
                                <div>
                                    <asp:Label ID="lbl5" runat="server" Text="Rate" CssClass="formLable"></asp:Label>
                                </div>
                                <div>
                                    <asp:TextBox ID="txt_rate" Width="200" runat="server" CssClass="txtbox"></asp:TextBox>
                                </div>
                            </div>
                        </div>
                        <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click"
                            CausesValidation="False" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:gridview>
</div>

C# code of ButtonAdd_Click()

if (ViewState["CurrentTable"] != null)
{
    DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
    DataRow drCurrentRow = null;
    if (dtCurrentTable.Rows.Count > 0)
    {
        for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
        {
            //extract the TextBox values
            TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("txt_type");
            TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("txt_total");
            TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("txt_max");
            TextBox box4 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("txt_min");
            TextBox box5 = (TextBox)Gridview1.Rows[rowIndex].Cells[5].FindControl("txt_rate");

            drCurrentRow = dtCurrentTable.NewRow();

            dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
            dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
            dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
            dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
            dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;

            rowIndex++;
        }
        dtCurrentTable.Rows.Add(drCurrentRow);
        ViewState["CurrentTable"] = dtCurrentTable;

        Gridview1.DataSource = dtCurrentTable;
        Gridview1.DataBind();
    }
}
else
{
    Response.Write("ViewState is null");
}

This question is related to c# asp.net webforms

The answer is


try this.

if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
                        //extract the TextBox values
                        TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_type");
                        TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_total");
                        TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_max");
                        TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_min");
                        TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[5].FindControl("txt_rate");

                        drCurrentRow = dtCurrentTable.NewRow();
                        drCurrentRow["RowNumber"] = i + 1;

                        dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                        dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                        dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
                        dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
                        dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;

                        rowIndex++;
                    }
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    ViewState["CurrentTable"] = dtCurrentTable;

                    Gridview1.DataSource = dtCurrentTable;
                    Gridview1.DataBind();
                }
            }
            else
            {
                Response.Write("ViewState is null");
            }

I was also getting same issue as i tried using value 0 in non-based indexing,i.e starting with 1, not with zero


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to webforms

ASP.NET Button to redirect to another page How to use the DropDownList's SelectedIndexChanged event "Specified argument was out of the range of valid values" The ScriptManager must appear before any controls that need it Check if Cookie Exists How to do a Jquery Callback after form submit? "The given path's format is not supported." A potentially dangerous Request.Path value was detected from the client (*) How to create <input type=“text”/> dynamically Create a HTML table where each TR is a FORM