Add dynamic Rows in ASP.Net GridView with TextBox and Delete functionality without PostBack

Last Reply one month ago By dharmendr

Posted one month ago

How to add Dynamic Rows in ASP.Net GridView Control with TextBoxes Without Post Back

Refrence to your code on below URL

Adding Dynamic Rows in ASP.Net GridView Control with TextBoxes

i want to add and delete rows without postback

please help me in this

regard thanks

Posted one month ago

Hi arehman,

Use UpdatePanel to avoid PostBack.

Place the GridView inside UpdatePanel.

Adding Dynamic Rows in ASP.NET GridView Control with TextBoxes and with Delete functionality

Check this example. Now please take its reference and correct your code.

HTML

<div>
    <asp:ScriptManager runat="server" />
    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false"
                OnRowCreated="Gridview1_RowCreated">
                <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="btnAdd" runat="server" Text="Add New Row" OnClick="btnAdd_Click" />
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:LinkButton ID="lnkDelete" runat="server" OnClick="lnkDelete_Click">Remove</asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
</div>

Namespaces

C#

using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;

VB.Net

Imports System.Collections.Specialized
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Text

Code

C#

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();
}
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++;
            }
            dtCurrentTable.Rows.Add(drCurrentRow);
            ViewState["CurrentTable"] = dtCurrentTable;

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

    //Set Previous Data on Postbacks
    SetPreviousData();
}
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++;

            }
        }
        // ViewState["CurrentTable"] = dt;

    }
}
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        SetInitialRow();
    }
}
protected void btnAdd_Click(object sender, EventArgs e)
{
    AddNewRowToGrid();
}
protected void btnSave_Click(object sender, EventArgs e)
{
    int rowIndex = 0;
    StringCollection sc = new StringCollection();
    if (ViewState["CurrentTable"] != null)
    {
        DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
        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");

                //get the values from the TextBoxes
                //then add it to the collections with a comma "," as the delimited values
                sc.Add(box1.Text + "," + box2.Text + "," + box3.Text);
                rowIndex++;
            }
            //Call the method for executing inserts
            InsertRecords(sc);
        }
    }
}
private void InsertRecords(StringCollection sc)
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
    StringBuilder sb = new StringBuilder(string.Empty);
    string[] splitItems = null;
    foreach (string item in sc)
    {

        const string sqlStatement = "INSERT INTO SampleTable (Column1,Column2,Column3) VALUES";
        if (item.Contains(","))
        {
            splitItems = item.Split(",".ToCharArray());
            sb.AppendFormat("{0}('{1}','{2}','{3}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2]);
        }
    }

    try
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();

        Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);

    }
    catch (System.Data.SqlClient.SqlException ex)
    {
        string msg = "Insert Error:";
        msg += ex.Message;
        throw new Exception(msg);

    }
    finally
    {
        conn.Close();
    }
}
protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataTable dt = (DataTable)ViewState["CurrentTable"];
        LinkButton lb = (LinkButton)e.Row.FindControl("lnkDelete");
        if (lb != null)
        {
            if (dt.Rows.Count > 1)
            {
                if (e.Row.RowIndex == dt.Rows.Count - 1)
                {
                    lb.Visible = false;
                }
            }
            else
            {
                lb.Visible = false;
            }
        }
    }
}
protected void lnkDelete_Click(object sender, EventArgs e)
{
    LinkButton lb = (LinkButton)sender;
    GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
    int rowID = gvRow.RowIndex + 1;
    if (ViewState["CurrentTable"] != null)
    {
        DataTable dt = (DataTable)ViewState["CurrentTable"];
        if (dt.Rows.Count > 1)
        {
            if (gvRow.RowIndex < dt.Rows.Count - 1)
            {
                //Remove the Selected Row data
                dt.Rows.Remove(dt.Rows[rowID]);
            }
        }
        //Store the current data in ViewState for future reference
        ViewState["CurrentTable"] = dt;
        //Re bind the GridView for the updated data
        Gridview1.DataSource = dt;
        Gridview1.DataBind();
    }

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

VB.Net

Private Sub SetInitialRow()
    Dim dt As DataTable = 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 = CType(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 = CType(Gridview1.Rows(rowIndex).Cells(1).FindControl("TextBox1"), TextBox)
                Dim box2 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(2).FindControl("TextBox2"), TextBox)
                Dim box3 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(3).FindControl("TextBox3"), TextBox)
                drCurrentRow = dtCurrentTable.NewRow()
                drCurrentRow("RowNumber") = i + 1
                drCurrentRow("Column1") = box1.Text
                drCurrentRow("Column2") = box2.Text
                drCurrentRow("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 = CType(ViewState("CurrentTable"), DataTable)
        If dt.Rows.Count > 0 Then
            For i As Integer = 1 To dt.Rows.Count - 1
                Dim box1 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(1).FindControl("TextBox1"), TextBox)
                Dim box2 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(2).FindControl("TextBox2"), TextBox)
                Dim box3 As TextBox = CType(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 Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        SetInitialRow()
    End If
End Sub

Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs)
    AddNewRowToGrid()
End Sub

Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim rowIndex As Integer = 0
    Dim sc As StringCollection = New StringCollection()
    If ViewState("CurrentTable") IsNot Nothing Then
        Dim dtCurrentTable As DataTable = CType(ViewState("CurrentTable"), DataTable)
        If dtCurrentTable.Rows.Count > 0 Then

            For i As Integer = 1 To dtCurrentTable.Rows.Count
                Dim box1 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(1).FindControl("TextBox1"), TextBox)
                Dim box2 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(2).FindControl("TextBox2"), TextBox)
                Dim box3 As TextBox = CType(Gridview1.Rows(rowIndex).Cells(3).FindControl("TextBox3"), TextBox)
                sc.Add(box1.Text & "," + box2.Text & "," + box3.Text)
                rowIndex += 1
            Next

            InsertRecords(sc)
        End If
    End If
End Sub

Private Sub InsertRecords(ByVal sc As StringCollection)
    Dim conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString)
    Dim sb As StringBuilder = New StringBuilder(String.Empty)
    Dim splitItems As String() = Nothing
    For Each item As String In sc
        Const sqlStatement As String = "INSERT INTO SampleTable (Column1,Column2,Column3) VALUES"
        If item.Contains(",") Then
            splitItems = item.Split(",".ToCharArray())
            sb.AppendFormat("{0}('{1}','{2}','{3}'); ", sqlStatement, splitItems(0), splitItems(1), splitItems(2))
        End If
    Next
    Try
        conn.Open()
        Dim cmd As SqlCommand = New SqlCommand(sb.ToString(), conn)
        cmd.CommandType = CommandType.Text
        cmd.ExecuteNonQuery()
        Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
    Catch ex As System.Data.SqlClient.SqlException
        Dim msg As String = "Insert Error:"
        msg += ex.Message
        Throw New Exception(msg)
    Finally
        conn.Close()
    End Try
End Sub

Protected Sub Gridview1_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim dt As DataTable = CType(ViewState("CurrentTable"), DataTable)
        Dim lb As LinkButton = CType(e.Row.FindControl("lnkDelete"), LinkButton)
        If lb IsNot Nothing Then
            If dt.Rows.Count > 1 Then
                If e.Row.RowIndex = dt.Rows.Count - 1 Then
                    lb.Visible = False
                End If
            Else
                lb.Visible = False
            End If
        End If
    End If
End Sub

Protected Sub lnkDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim lb As LinkButton = CType(sender, LinkButton)
    Dim gvRow As GridViewRow = CType(lb.NamingContainer, GridViewRow)
    Dim rowID As Integer = gvRow.RowIndex + 1
    If ViewState("CurrentTable") IsNot Nothing Then
        Dim dt As DataTable = CType(ViewState("CurrentTable"), DataTable)
        If dt.Rows.Count > 1 Then
            If gvRow.RowIndex < dt.Rows.Count - 1 Then
                dt.Rows.Remove(dt.Rows(rowID))
            End If
        End If
        ViewState("CurrentTable") = dt
        Gridview1.DataSource = dt
        Gridview1.DataBind()
    End If

    SetPreviousData()
End Sub

Screenshot