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.

9 comments:

  1. Very Help ful code. i like these.
    and it actually work good.
    I need to generate multiple rows at a time.
    Can you help me for these. . ..
    Please post code for that.

    ReplyDelete
    Replies
    1. Thanks for your appreciation, have you test this code in browser? You can generate multiple rows (row after row) when you click on ButtonAdd.

      Is that so or your case is different. Let me know if any query remains. Cheers

      Delete
  2. HEllo
    I WANT TO DO THE ITEM DETAILS ENTRY TABLE...
    LIVE ONE PAGE CONTAIN

    First Name :- txt1
    Last Name:- txt2
    (Imagine this as a GridView)
    Makrs1 Makrs2 Makrs3 Makrs4
    Dynamic Rowsssssssssssssssssssssssssssss

    Now here is the Question
    When i lost my foucs from txt2 Automatically Dynamic TextBox3 Will be in the First row below Marks1
    Imagine that i has enter the Data in the Marks1 Column Now when i press Tab And reelase From that TextBox3

    Then Textbox3 (Dynamic Textbox3) Will move from Marks2 Column
    Here i has enter the Data in the Marks2 Column Now when i press Tab And reelase From that TextBox3

    Then Textbox3 (Dynamic Textbox3) Will move from Marks3 Column
    So Data Will be Display Like This

    Marks1 Marks2 MArks3 Marks4
    70 90 Now here is my Dynamic Textboc3

    Now when i enter my marks3 and press Tab The Dhyamic Texbox3 Move to Mark4 Column

    HERE AGAIN When I enter The Data and release the Textbox3 Press Tab
    Then AUTOMATICALLY NEW ROW WILL BE GENERATED AND AGAIN DYNAMIC TEXTBOX3 WILL POINT THE 2nd ROW MARKS1 Column and so on.....

    AT THE END WHEN I PRESS ON SUBMIT BUTTON FNAME AND LNAME WILL INSERT DATA IN MASTER TABLE AND STUD ID IS PK AND FK IN STUDENT MARKS TABLE... SO MARKS DATA WILL BE INSERTD INTO THE STUDENTMARKS TABLE



    ReplyDelete
  3. Its really helpful for me to understand where we i lost in my previous interview. Thanks.
    If anyone wants to Learn .NET in Chennai go to the Besant Technologies which is No.1 Training Institute in Chennai.

    http://www.besanttechnologies.com/training-courses/dot-net-training

    ReplyDelete
  4. Thanks for sharing this useful information..Its really very informative.

    Dot Net Course in Chennai

    ReplyDelete
  5. how can use dynamic row in grid view, when one row complete then auto genrate new row for as sql table

    ReplyDelete