Dynamically Add New Row in GridView Using Asp.Net

Introduction:
I decided to write this article because this has been asked so many times before at the forums(http://forums.asp.net) . Basically, this example shows on how to generate a Row in GridView with TextBoxes when clicking a Button that is residing inside a GridView Footer.

To get started, let’s grab a GridView control from the Visual Studio Toolbox and put it in the WebForm. The mark up would look something like this:

<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
        <Columns>
        <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
        <asp:TemplateField HeaderText="Header 1">
            <ItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Header 2">
            <ItemTemplate>
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Header 3">
            <ItemTemplate>
                 <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
            </ItemTemplate>
            <FooterStyle HorizontalAlign="Right" />
            <FooterTemplate>
             <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" />
            </FooterTemplate>
        </asp:TemplateField>
        </Columns>
</asp:gridview>

Since this demo is intended to generate rows of TextBoxes in GridView, then we set up some TemplateFields columns so that GridView will automatically generates TextBoxes when a new row is being added.

As you can see I have set up a BoundField Column for displaying the RowNumber and sep up three TemplateField Columns in the Grid and added each columns a TextBox Control. You would also noticed that I have added a Button Control under the FooterTemplate at the last column in the GridView.

Note: Since we are added a Control in the GridView footer, then be sure to set ShowFooter to TRUE in the GridView.

Now let’s switch to the Code behind part of the webform.

As you may know, the GridView control will not show in the page once there is no data associated on it. So the first thing we need here is to set an initial data in the  GridView  Control. To do this, we can use a DataTable for binding our GridView.

Here’s the code block below:

    private void SetInitialRow()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Column1", typeof(string)));
        dt.Columns.Add(new DataColumn("Column2", typeof(string)));
        dt.Columns.Add(new DataColumn("Column3", typeof(string)));
        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Column1"] = string.Empty;
        dr["Column2"] = string.Empty;
        dr["Column3"] = string.Empty;
        dt.Rows.Add(dr);
        //dr = dt.NewRow();

        //Store the DataTable in ViewState
        ViewState["CurrentTable"] = dt;

        Gridview1.DataSource = dt;
        Gridview1.DataBind();
    }

As you can see, we defined four Columns in the DataTable called RowNumber, Column1, Column2 and Column3. The RowNumber column  will serve as the key for generating the rows in the GridView. Noticed that for Columns  1,2 and 3, I assigned an empty value for that columns since the GridView will be generated for the first time. You also noticed that I store the DataTable in ViewState so that we can reference the current data associated within the DataTable when it postbacks.

Now lets call the method above in Page_Load event:

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

Running the codes above will give us this output below:


Now let’s create the method for generating the rows when clicking the Button. Here are the code blocks below:

    private void AddNewRowToGrid()
    {
        int rowIndex =0;

        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("TextBox1");
                    TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                    TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");

                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;
                    drCurrentRow["Column1"] = box1.Text;
                    drCurrentRow["Column2"] = box2.Text;
                    drCurrentRow["Column3"] = box3.Text;

                    rowIndex++;
                }
                //add new row to DataTable
                dtCurrentTable.Rows.Add(drCurrentRow);
                //Store the current data to ViewState
                ViewState["CurrentTable"] = dtCurrentTable;

                //Rebind the Grid with the current data
                Gridview1.DataSource = dtCurrentTable;
                Gridview1.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }

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

As a summary, the code above gets the previous data stored from the viewstate and set the data stored from it into a DataTable so that we can add a new row based from the value entered from the TextBox.

You will also noticed that we call the method SetPreviousData() at the bottom part of the codes above. Now where is that method?  Below are the code blocks for that method:

    private void SetPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 1; i < dt.Rows.Count; i++)
                {
                    TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                    TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                    TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");

                    box1.Text = dt.Rows[i]["Column1"].ToString();
                    box2.Text = dt.Rows[i]["Column2"].ToString();
                    box3.Text = dt.Rows[i]["Column3"].ToString();
                  
                    rowIndex++;

                }
            }
        }
    }

Now, since the methods are all set then we can call this at Button Click event of the Button.

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


As you can see the code above is very straight forward and self explanatory.  Running the code above will give us this output below:

0 comments:

Post a Comment