How to Add Gridview Rows Dynamically on Button Click in Asp.net - c# and VB.Net

In this tutorial i am going to explain how to add new rows and also delete particular row to gridview on click of button in asp.net using c#, vb.net with example. and also share with you how to adding gridview rows dynamically on button click in asp.net with using c#, vb.net with example.

For that you need to write aspx code.

HTML Source Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Add or Delete new row into gridview on click of button in asp.net </title>
    <style type="text/css">
        .GridviewDiv {
            font-size100%;  
            color#303933;
        }
 
        .headerstyle {
            color#FFFFFF;
            border-right-colorblue;
            border-bottom-colorblue;
            background-color#df5015;;
            padding0.5em 0.5em 0.5em 0.5em;
            text-aligncenter;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div class="GridviewDiv">
            <asp:GridView runat="server" ID="gvDetails" ShowFooter="true" AllowPaging="true" PageSize="10" AutoGenerateColumns="false" ShowHeaderWhenEmpty="true" OnRowDeleting="gvDetails_RowDeleting" Height="329px" Width="594px">
                <HeaderStyle CssClass="headerstyle" />
                <Columns>
                    <asp:BoundField DataField="rowid" HeaderText="Row Id" ReadOnly="true" />
                    <asp:TemplateField HeaderText="Product Name">
                        <ItemTemplate>
                            <asp:TextBox ID="txtName" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Price">
                        <ItemTemplate>
                            <asp:TextBox ID="txtPrice" runat="server" />
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ShowDeleteButton="true" />
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

C# Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridview();
        }
    }
    protected void BindGridview()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("rowid"typeof(int));
        dt.Columns.Add("productname"typeof(string));
        dt.Columns.Add("price"typeof(string));
        DataRow dr = dt.NewRow();
        dr["rowid"] = 1;
        dr["productname"] = string.Empty;
        dr["price"] = string.Empty;
        dt.Rows.Add(dr);
        ViewState["Curtbl"] = dt;
        gvDetails.DataSource = dt;
        gvDetails.DataBind();
    }
    private void AddNewRow()
    {
        int rowIndex = 0;
 
        if (ViewState["Curtbl"] != null)
        {
            DataTable dt = (DataTable)ViewState["Curtbl"];
            DataRow drCurrentRow = null;
            if (dt.Rows.Count > 0)
            {
                for (int i = 1; i <= dt.Rows.Count; i++)
                {
                    TextBox txtname = (TextBox)gvDetails.Rows[rowIndex].Cells[1].FindControl("txtName");
                    TextBox txtprice = (TextBox)gvDetails.Rows[rowIndex].Cells[2].FindControl("txtPrice");
                    drCurrentRow = dt.NewRow();
                    drCurrentRow["rowid"] = i + 1;
                    dt.Rows[i - 1]["productname"] = txtname.Text;
                    dt.Rows[i - 1]["price"] = txtprice.Text;
                    rowIndex++;
                }
                dt.Rows.Add(drCurrentRow);
                ViewState["Curtbl"] = dt;
                gvDetails.DataSource = dt;
                gvDetails.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState Value is Null");
        }
        SetOldData();
    }
    private void SetOldData()
    {
        int rowIndex = 0;
        if (ViewState["Curtbl"] != null)
        {
            DataTable dt = (DataTable)ViewState["Curtbl"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TextBox txtname = (TextBox)gvDetails.Rows[rowIndex].Cells[1].FindControl("txtName");
                    TextBox txtprice = (TextBox)gvDetails.Rows[rowIndex].Cells[2].FindControl("txtPrice");
                    txtname.Text = dt.Rows[i]["productname"].ToString();
                    txtprice.Text = dt.Rows[i]["price"].ToString();
                    rowIndex++;
                }
            }
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        AddNewRow();
    }
    protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        if (ViewState["Curtbl"] != null)
        {
            DataTable dt = (DataTable)ViewState["Curtbl"];
            DataRow drCurrentRow = null;
            int rowIndex = Convert.ToInt32(e.RowIndex);
            if (dt.Rows.Count > 1)
            {
                dt.Rows.Remove(dt.Rows[rowIndex]);
                drCurrentRow = dt.NewRow();
                ViewState["Curtbl"] = dt;
                gvDetails.DataSource = dt;
                gvDetails.DataBind();
                for (int i = 0; i < gvDetails.Rows.Count - 1; i++)
                {
                    gvDetails.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                }
                SetOldData();
 
            }
        }
    }
}

Vb.Net Code:

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
 
Partial Class VBCode
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgsHandles Me.Load
        If Not IsPostBack Then
            BindGridview()
        End If
    End Sub
    Protected Sub BindGridview()
        Dim dt As New DataTable()
        dt.Columns.Add("rowid"GetType(Integer))
        dt.Columns.Add("productname"GetType(String))
        dt.Columns.Add("price"GetType(String))
        Dim dr As DataRow = dt.NewRow()
        dr("rowid") = 1
        dr("productname") = String.Empty
        dr("price") = String.Empty
        dt.Rows.Add(dr)
        ViewState("Curtbl") = dt
        gvDetails.DataSource = dt
        gvDetails.DataBind()
    End Sub
 
    Private Sub AddNewRow()
        Dim rowIndex As Integer = 0
 
        If ViewState("Curtbl"IsNot Nothing Then
            Dim dt As DataTable = DirectCast(ViewState("Curtbl"), DataTable)
            Dim drCurrentRow As DataRow = Nothing
            If dt.Rows.Count > 0 Then
                For i As Integer = 1 To dt.Rows.Count
                    Dim txtname As TextBox = DirectCast(gvDetails.Rows(rowIndex).Cells(1).FindControl("txtName"), TextBox)
                    Dim txtprice As TextBox = DirectCast(gvDetails.Rows(rowIndex).Cells(2).FindControl("txtPrice"), TextBox)
                    drCurrentRow = dt.NewRow()
                    drCurrentRow("rowid") = i + 1
                    dt.Rows(i - 1)("productname") = txtname.Text
                    dt.Rows(i - 1)("price") = txtprice.Text
                    rowIndex += 1
                Next
                dt.Rows.Add(drCurrentRow)
                ViewState("Curtbl") = dt
                gvDetails.DataSource = dt
                gvDetails.DataBind()
            End If
        Else
            Response.Write("ViewState Value is Null")
        End If
        SetOldData()
    End Sub
    Private Sub SetOldData()
        Dim rowIndex As Integer = 0
        If ViewState("Curtbl"IsNot Nothing Then
            Dim dt As DataTable = DirectCast(ViewState("Curtbl"), DataTable)
            If dt.Rows.Count > 0 Then
                For i As Integer = 0 To dt.Rows.Count - 1
                    Dim txtname As TextBox = DirectCast(gvDetails.Rows(rowIndex).Cells(1).FindControl("txtName"), TextBox)
                    Dim txtprice As TextBox = DirectCast(gvDetails.Rows(rowIndex).Cells(2).FindControl("txtPrice"), TextBox)
                    txtname.Text = dt.Rows(i)("productname").ToString()
                    txtprice.Text = dt.Rows(i)("price").ToString()
                    rowIndex += 1
                Next
            End If
        End If
    End Sub
    Protected Sub btnAdd_Click(ByVal sender As ObjectByVal e As EventArgs)
        AddNewRow()
    End Sub
    Protected Sub gvDetails_RowDeleting(ByVal sender As ObjectByVal e As GridViewDeleteEventArgs)
        If ViewState("Curtbl"IsNot Nothing Then
            Dim dt As DataTable = DirectCast(ViewState("Curtbl"), DataTable)
            Dim drCurrentRow As DataRow = Nothing
            Dim rowIndex As Integer = Convert.ToInt32(e.RowIndex)
            If dt.Rows.Count > 1 Then
                dt.Rows.Remove(dt.Rows(rowIndex))
                drCurrentRow = dt.NewRow()
                ViewState("Curtbl") = dt
                gvDetails.DataSource = dt
                gvDetails.DataBind()
 
                For i As Integer = 0 To gvDetails.Rows.Count - 2
                    gvDetails.Rows(i).Cells(0).Text = Convert.ToString(i + 1)
                Next
                SetOldData()
            End If
        End If
    End Sub
End Class

DEMO:


Gridview Result
Previous
Next Post »

If you have any kind of question about any post, Feel free to ask.You can simply drop a comment below post. Your feedback and suggestions will be highly appreciated. ConversionConversion EmoticonEmoticon