Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Remove Add New Row to GridView on Button Click in ASP.Net using C#, VB.NET Example

Jul 22, 2015
Introduction

Here I will explain how to delete / remove or add new rows to
gridview on button click in asp.net using c#, vb.net with example or dynamically adding gridview rows on button click in asp.net using c#, vb.net with example.

Description:
  
In previous articles I explained
crud operations (insert, update, delete) in gridview in asp.net, gridview examples in asp.net, display images from database using handler in asp.net, Bind Dropdownlist selected value in asp.net gridview and many articles relating to gridview, asp.net, c#,vb.net and jQuery. Now I will explain how to delete or add new rows to gridview on button click in asp.net using c#, vb.net with example.

Now open your aspx page and write the following code


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Delete Add new row to gridview on button click in asp.net </title>
<style type="text/css">
.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}
.headerstyle
{
color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;background-color: #df5015;padding:0.5em 0.5em 0.5em 0.5em;text-align:center;
}
</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">
<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>

Now add following namespaces in code behind

C# Code


using System;
using System.Web.UI.WebControls;
using System.Data;

After completion of adding namespaces you need to write the code like as shown below


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.Web.UI.WebControls
Imports System.Data

Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles 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 Object, ByVal e As EventArgs)
AddNewRow()
End Sub
Protected Sub gvDetails_RowDeleting(ByVal sender As Object, ByVal 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


Remove Add New Row to GridView on Button Click in ASP.Net using C#, VB.NET Example
Download Sample Code Attached



If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

8 comments :

Naveen Muruga said...

dt.Rows(i - 1)("price") = txtprice.Text

object reference not set error will shown

Unknown said...

May I know how to delete the first row?

Unknown said...

How to Remove delete link from 1st row because it can not be deleted...
pls reply as soon as.....

Yamraj said...

Hi,

I had used same code for girdview with different columns as I needed, there are almost 20+ columns.

My question is, it will take long time to execute same code. Whats the problem with this,

Thanks,
Yamraj Pandya

Unknown said...

what is viewstate Curtbl

Arvind Kumar said...

After deleting any row from GridView, SetOldData() function is not working..

Unknown said...

how to deal with fileupload control?

Anonymous said...

public Class1 obj = new Class1();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillgrid();
}
}
public void fillgrid()
{
DataSet ds = obj.exedataset("select * from Course");
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
String s = "insert into Course values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')";
obj.exenonquery(s);
obj.dbclose();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
fillgrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
String id = GridView1.DataKeys[e.RowIndex].Value.ToString();
TextBox txt = new TextBox();
txt = (TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0];
TextBox txt1 = new TextBox();
txt1 = (TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0];
TextBox txt2 = new TextBox();
txt2 = (TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0];
int i = obj.exenonquery("update Course set cname='" + txt.Text + "',fees='" + txt1.Text + "',seats='" + txt2.Text + "' where id='" + id + "'");
GridView1.EditIndex = -1;
fillgrid();
}

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
fillgrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
String id = GridView1.DataKeys[e.RowIndex].Value.ToString();
obj.exenonquery("delete from Course where id=" + id + "");
fillgrid();
}
protected void Button2_Click(object sender, EventArgs e)
{
HtmlInputCheckBox chk;
foreach (GridViewRow dr in GridView1.Rows)
{
chk = (HtmlInputCheckBox)dr.FindControl("ch");
{
if (chk.Checked)
{
obj.exenonquery("delete from Course where id=" + chk.Value + "");
}
}
fillgrid();
}
}

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
fillgrid();
}

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.