Tuesday, February 21

Adding Dynamic Rows in ASP.Net GridView Control with TextBoxes

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


Source Code:-



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicTextBoxCreateOnly.aspx.cs" Inherits="DynamicTextBoxCreateOnly" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        <Columns>
        <asp:BoundField DataField="Row" HeaderText="Row" />
        <asp:TemplateField HeaderText="Shiba1">
        <ItemTemplate>
            <asp:TextBox ID="shibashish1" runat="server"></asp:TextBox>
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Shiba2">
        <ItemTemplate>
            <asp:TextBox ID="shibashish2" runat="server"></asp:TextBox>
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Shiba3">
        <ItemTemplate>
            <asp:TextBox ID="shibashish3" runat="server"></asp:TextBox>
        </ItemTemplate>
        </asp:TemplateField>
        </Columns>
        </asp:GridView>
    </div>
    <div align="center" style="width: 802px">
        <asp:Button ID="AddTextbox" runat="server" Text="AddTextbox" 
            onclick="AddTextbox_Click" />


    </div>
     <div>
    </div>
    </form>
</body>
</html>


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

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:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class DynamicTextBoxCreateOnly : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            SetInitialRow();
        }
    }
    private void SetInitialRow()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("Row", 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["Row"] = 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();
    }
    private void SetPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TextBox box1 = (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("shibashish1");
                    TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("shibashish2");
                    TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("shibashish3");

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

                    rowIndex++;
                }
            }
        }
    }
    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("shibashish1");
                    TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("shibashish2");
                    TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("shibashish3");

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

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

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

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

        //Set Previous Data on Postbacks
        SetPreviousData();
    }
    protected void AddTextbox_Click(object sender, EventArgs e)
    {
        AddNewRowToGrid();
    }
}

Page View:-

Running Mode:-






 Download the sample source code using the link below


Thanks shibashish Mohanty

12 comments:

  1. Good morning and thank you so much shivashish

    This code is running perfectly.

    YOu have mentioned the code which is very easy to understand.

    I really appreciate.

    Thank you so much again.

    ReplyDelete
  2. Dear shivashish.

    I am tryinging to add a edit, update and delete button at run time and fetch the data from database but did not success.

    please let me know the code for this.

    one thing again as you have given the code insert the row at run time but how we can insert the data with this text box using insert button.

    Thanks and regards.

    ReplyDelete
    Replies
    1. sure i will work for that and shortly i am going to post that one thanks a lot

      Delete
    2. if you want to save data in database then go for this link
      http://shibashishdotnetocean.blogspot.in/2012/02/save-dynamic-textbox-values-from.html

      Delete
  3. Thank you... nice one...

    ReplyDelete
  4. That's au very nice article, but I have a problem when I display Data and I want to Add new Row.
    Can you help me ?
    Thank you :)

    ReplyDelete
    Replies
    1. http://shibashishdotnetocean.blogspot.in/2012/08/adding-and-removing-dynamic-rows-in.html
      check this one
      regards
      shibashish mohanty

      Delete
    2. Thank you :)

      Delete
  5. hi,

    can you help me??how about i want to make 12rows at first time load page.then only user add new 1 row..i tried but it failed at the set previous data function.all the 12 rows data is gone!please help me.i really need your help.urgent!

    ReplyDelete
  6. Hi, I am working on project on ASP.NET and Oracle 11g Express. I need to search a table, retrieve data and populate a gridview or list view whichever is more efficient. Any ideas i will really appreciate. Code sample will even be more handy. Thanks

    ReplyDelete
  7. Hie I am trying to do this in using vb. and would also like to calculate totals from the textboxes here is my code so far. Please help.

    Imports System.Data
    Public Class Trial
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
    SetInitialRow()
    End If
    End Sub

    Protected Sub Gridview1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Gridview1.SelectedIndexChanged

    End Sub

    Private Sub SetInitialRow()

    Dim dt As New DataTable()
    Dim dr As DataRow = Nothing
    dt.Columns.Add(New DataColumn("RowNumber", GetType(String)))
    dt.Columns.Add(New DataColumn("Column1", GetType(String)))
    dt.Columns.Add(New DataColumn("Column2", GetType(String)))
    dt.Columns.Add(New DataColumn("Column3", GetType(String)))
    dr = dt.NewRow()
    dr("RowNumber") = 1
    dr("Column1") = String.Empty
    dr("Column2") = String.Empty
    dr("Column3") = String.Empty
    dt.Rows.Add(dr)
    ViewState("CurrentTable") = dt
    Gridview1.DataSource = dt
    Gridview1.DataBind()

    End Sub


    Private Sub AddNewRowToGrid()

    Dim rowIndex As Integer = 0

    If ViewState("CurrentTable") IsNot Nothing Then
    Dim dtCurrentTable As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
    Dim drCurrentRow As DataRow = Nothing

    If dtCurrentTable.Rows.Count > 0 Then
    For i As Integer = 1 To dtCurrentTable.Rows.Count
    Dim box1 As TextBox = DirectCast(Gridview1.Rows(rowIndex).Cells(1).FindControl("TextBox1"), TextBox)
    Dim box2 As TextBox = DirectCast(Gridview1.Rows(rowIndex).Cells(2).FindControl("TextBox2"), TextBox)
    Dim box3 As TextBox = DirectCast(Gridview1.Rows(rowIndex).Cells(3).FindControl("TextBox3"), TextBox)
    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
    rowIndex += 1
    Next

    dtCurrentTable.Rows.Add(drCurrentRow)
    ViewState("CurrentTable") = dtCurrentTable
    Gridview1.DataSource = dtCurrentTable
    Gridview1.DataBind()

    End If
    Else
    Response.Write("ViewState is null")
    End If
    SetPreviousData()

    End Sub

    Private Sub SetPreviousData()

    Dim rowIndex As Integer = 0

    If ViewState("CurrentTable") IsNot Nothing Then
    Dim dt As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
    If dt.Rows.Count > 0 Then
    For i As Integer = 0 To dt.Rows.Count - 1
    Dim box1 As TextBox = DirectCast(Gridview1.Rows(rowIndex).Cells(1).FindControl("TextBox1"), TextBox)
    Dim box2 As TextBox = DirectCast(Gridview1.Rows(rowIndex).Cells(2).FindControl("TextBox2"), TextBox)
    Dim box3 As TextBox = DirectCast(Gridview1.Rows(rowIndex).Cells(3).FindControl("TextBox3"), TextBox)
    box1.Text = dt.Rows(i)("Column1").ToString()
    box2.Text = dt.Rows(i)("Column2").ToString()
    box3.Text = dt.Rows(i)("Column3").ToString()
    rowIndex += 1
    Next
    End If
    End If

    End Sub

    Protected Sub ButtonAdd_Click(sender As Object, e As EventArgs)

    AddNewRowToGrid()

    End Sub

    End Class



    ReplyDelete

Please don't spam, spam comments is not allowed here.

ShibashishMnty
shibashish mohanty