May 14, 2013

Adding Dynamic Rows in ASP.Net GridView Control with TextBoxes

Now a days on Asp.Net Forum, many people ask how to add rows dynamically to gridview. In this example I am show you to generate a row in Gridview on button click.

To get started, lets use GridView control. Modify the markup of code as:

<asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:TextBox ID="NameText" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Country">
            <ItemTemplate>
                <asp:TextBox ID="CountryText" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="City">
            <ItemTemplate>
                <asp:TextBox ID="CityText" runat="server" />
            </ItemTemplate>
            <FooterStyle HorizontalAlign="Right" />
            <FooterTemplate>
                <asp:Button ID="AddRowButton" runat="server" Text="Add New Row" 
                    OnClick="ButtonAdd_Click" />
            </FooterTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Now lets switch to the code behind part:

private void SetInitialRowToGrid()
{
    // Initialize and Set initial row of Datatable
    var tempDataTable = new DataTable();
    tempDataTable.Columns.Add("RowNumber");
    tempDataTable.Columns.Add("NameText");
    tempDataTable.Columns.Add("CountryText");
    tempDataTable.Columns.Add("CityText");
    tempDataTable.Rows.Add("1", "", "", "");

    // Store that datatable into viewstate
    ViewState["TempTable"] = tempDataTable;

    // Attach Gridview Datasource to datatable
    GridView1.DataSource = tempDataTable;
    GridView1.DataBind();
}

private void AddNewRowToGrid()
{
    int rowIndex = 0;

    if (ViewState["TempTable"] != null)
    {
        // Get TempTable from viewstate
        var tempTable = (DataTable)ViewState["TempTable"];
        DataRow tempRow = null;

        if (tempTable.Rows.Count > 0)
        {
            for (int i = 1; i <= tempTable.Rows.Count; i++)
            {
                // Get Grid's TextBox values
                var nameText = 
                    (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("NameText");
                var countryText = 
                    (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("CountryText");
                var cityText = 
                    (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("CityText");

                // Create new row and update Row Number
                tempRow = tempTable.NewRow();
                tempRow["RowNumber"] = i + 1;

                tempTable.Rows[i - 1]["NameText"] = nameText.Text;
                tempTable.Rows[i - 1]["CountryText"] = countryText.Text;
                tempTable.Rows[i - 1]["CityText"] = cityText.Text;

                rowIndex++;
            }

            // Add data to datatable and viewstate
            tempTable.Rows.Add(tempRow);
            ViewState["TempTable"] = tempTable;

            // Attach Gridview Datasource to datatable
            GridView1.DataSource = tempTable;
            GridView1.DataBind();
        }
    }

    //Set Previous Data on Postbacks
    SetPreviousData();
}

private void SetPreviousData()
{
    int rowIndex = 0;

    if (ViewState["TempTable"] != null)
    {
        var tempTable = (DataTable)ViewState["TempTable"];

        if (tempTable.Rows.Count > 0)
        {
            for (int i = 0; i < tempTable.Rows.Count; i++)
            {
                var nameText = 
                    (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("NameText");
                var countryText = 
                    (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("CountryText");
                var cityText = 
                    (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("CityText");

                nameText.Text = tempTable.Rows[i]["NameText"].ToString();
                countryText.Text = tempTable.Rows[i]["CountryText"].ToString();
                cityText.Text = tempTable.Rows[i]["CityText"].ToString();

                rowIndex++;
            }
        }
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.SetInitialRowToGrid();
    }
}

protected void ButtonAdd_Click(object sender, EventArgs e)
{
    AddNewRowToGrid();
}

Hope you will find this post useful.