Article
    C#
    ADO.Net
    .NET
    ASP.Net & Web Forms
    Custom Controls
    Web Development
    Exception Handling
    XML
    Database
    Security in .Net
    Testing
    Web Services
    Windows Services
    Windows Controls
    WCF
    AJAX
    WPF
    XAML
    Reporting
    Setup
    VB.Net
    LINQ
    JQuery
    SilverLight
    JavaScript
    HTML5
    Crystal Report
    Cloud Computing
    Share Point
    Visual C++
    MVC
    Android
    PHP
    Java
    HTML
    WordPress
    Joomla
    Products
    Drupal
    Windows Phone
    JSON
    LightSwitch
    iPhone/iPad
    Ruby on Rails
    IIS 7
    Windows 8
    CSS/CSS3
    Excel
    MS Access
    Shortcut Keys
    Visual SourceSafe
    Team Foundation Server
    APIs
Follow Us
Follow _MindStick_ on Twitter View MindStick Software's LinkedIn profile View MindStick Software's Facebook profile
Top Contributor
Advertisement
Advertise with Us
Mindstick
Article Article  Forum Forum  Blog Blog  Quiz Quiz  Beginner Beginner  Careers Careers  Contact Contact  Login Login  
Home | Product | Services | About Us | Interview | DeveloperSection | Submit an Article | Submit Blog

Home >> ASP.Net & Web Forms >> Insert, Delete, Update in GridView in ASP.Net using C#
Insert, Delete, Update in GridView in ASP.Net using C#
Insert, Delete, Update in GridView in ASP.Net using C#


by AVADHESH PATEL on 8/6/2012 3:05:56 PM

Views: 32344       Comments: 5

Insert, Delete, Update in GridView in ASP.Net using C#

This article will be very useful to all users who are working with ASP.NET GridView control. Here, I’m explaining how to work with the GridView control in ASP.NET. I will explain here how to insert, delete and update record in GridView. In this article I have also mention that how to apply validation in Asp.Net GridView control. Implementation Steps are given below-

Step 1:- Create Database in SqlServer and create a table within it here I have created a table with name“GridView”

Insert, Delete, Update in GridView in ASP.Net using C#

Step 2:- Add connection string in web.config file as give below.

<configuration>

                <connectionStrings>

                                 <add name="dbconnection" providerName="System.Data.SqlClient"

                                    connectionString="Data Source=.;Initial Catalog=avi;User Id=avisqlserver;         password=123456" />

                </connectionStrings>

</configuration>

 

Step 3:- Drag a GridView control from Toolbox on “aspx” page.

Step 4:- Write down the following code on aspx” page

<body>

    <form id="form1" runat="server">

    <div>

   

        <asp:GridView ID="GridView1" runat="server" ShowHeaderWhenEmpty="True"

            AutoGenerateColumns="False" onrowdeleting="RowDeleting"

            OnRowCancelingEdit="cancelRecord" OnRowEditing="editRecord"

            OnRowUpdating="updateRecord" CellPadding="4"

            EnableModelValidation="True" GridLines="None" Width="1297px"

            ForeColor="#333333" >

            <RowStyle HorizontalAlign="Center" />

            <AlternatingRowStyle BackColor="White" />

            <EditRowStyle BackColor="#7C6F57" />

            <FooterStyle BackColor="#1C5E55" ForeColor="White" Font-Bold="True" />

            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />

            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />

            <RowStyle BackColor="#E3EAEB" />

            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />

 

            <Columns>

 

            <asp:TemplateField>

            <HeaderTemplate>Id</HeaderTemplate>

            <ItemTemplate>

            <asp:Label ID ="lblId" runat="server" Text='<%#Bind("id")%>'></asp:Label>

            </ItemTemplate>

            <%--<FooterTemplate>

            <asp:Label ID ="lblNewId" runat="server" ></asp:Label>

            </FooterTemplate>--%>

            </asp:TemplateField>

 

            <asp:TemplateField>

            <HeaderTemplate>Name</HeaderTemplate>

            <ItemTemplate>

            <asp:Label ID ="lblName" runat="server" Text='<%#Bind("name") %>'></asp:Label>

            </ItemTemplate>

            <EditItemTemplate>

            <asp:TextBox ID="txtName" runat="server" Text='<%#Bind("name") %>' MaxLength="50"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtName" runat="server" Text="*" ToolTip="Enter name" ControlToValidate="txtName"></asp:RequiredFieldValidator>

            <asp:RegularExpressionValidator ID="revtxtName" runat="server" Text="*" ToolTip="Enter alphabate " ControlToValidate="txtName" ValidationExpression="^[a-zA-Z'.\s]{1,40}$"></asp:RegularExpressionValidator>

           

            </EditItemTemplate>

            <FooterTemplate>

            <asp:TextBox ID="txtNewName" runat="server" MaxLength="50"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtNewName" runat="server" Text="*" ToolTip="Enter name" ControlToValidate="txtNewName"></asp:RequiredFieldValidator>

            <asp:RegularExpressionValidator ID="revtxtNewName" runat="server" Text="*" ToolTip="Enter alphabate " ControlToValidate="txtNewName" ValidationExpression="^[a-zA-Z'.\s]{1,40}$"></asp:RegularExpressionValidator>

          

            </FooterTemplate>

            </asp:TemplateField>

           

            <asp:TemplateField>

            <HeaderTemplate>Age</HeaderTemplate>

            <ItemTemplate>

            <asp:Label ID="lblAge" runat ="server" Text='<%#Bind("age") %>'></asp:Label>

            </ItemTemplate>

            <EditItemTemplate>

            <asp:TextBox ID ="txtAge" runat="server" Text='<%#Bind("age") %>' MaxLength="2"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtAge" runat="server" Text="*" ToolTip="Enter age" ControlToValidate="txtAge"></asp:RequiredFieldValidator>

            <asp:RegularExpressionValidator ID="revtxtAge" runat="server" Text="*" ToolTip="Enter numeric value" ControlToValidate="txtAge" ValidationExpression="^[0-9]+$"></asp:RegularExpressionValidator>

          

            </EditItemTemplate>

            <FooterTemplate>

            <asp:TextBox ID="txtNewAge" runat="server" MaxLength="2"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtNewAge" runat="server" Text="*" ToolTip="Enter age" ControlToValidate="txtNewAge"></asp:RequiredFieldValidator>

            <asp:RegularExpressionValidator ID="revNewtxtAge" runat="server" Text="*" ToolTip="Enter numeric value" ControlToValidate="txtNewAge" ValidationExpression="^[0-9]+$"></asp:RegularExpressionValidator>

            </FooterTemplate>

            </asp:TemplateField>

 

            <asp:TemplateField>

            <HeaderTemplate>Salary</HeaderTemplate>

            <ItemTemplate>

            <asp:Label ID = "lblSalary" runat="server" Text='<%#Bind("salary") %>'></asp:Label>

            </ItemTemplate>

            <EditItemTemplate>

            <asp:TextBox ID="txtSalary" runat="server" Text='<%#Bind("salary") %>'  MaxLength="10"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtSalary" runat="server" Text="*"  ToolTip="Enter salary" ControlToValidate="txtSalary"></asp:RequiredFieldValidator>

            <asp:RegularExpressionValidator ID="revtxtSalary" runat="server" Text="*" ToolTip="Enter numeric value" ControlToValidate="txtSalary" ValidationExpression="^[0-9]+$"></asp:RegularExpressionValidator>

          

            </EditItemTemplate>

            <FooterTemplate>

            <asp:TextBox ID="txtNewSalary" runat="server" MaxLength="10"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtNewSalary" runat="server" Text="*"  ToolTip="Enter salary" ControlToValidate="txtNewSalary"></asp:RequiredFieldValidator>

            <asp:RegularExpressionValidator ID="revtxtNewSalary" runat="server" Text="*" ToolTip="Enter numeric value" ControlToValidate="txtNewSalary" ValidationExpression="^[0-9]+$"></asp:RegularExpressionValidator>

            </FooterTemplate>

            </asp:TemplateField>

 

            <asp:TemplateField>

            <HeaderTemplate>Country</HeaderTemplate>

            <ItemTemplate>

            <asp:Label ID = "lblCountry" runat="server" Text='<%#Bind("country") %>'></asp:Label>

            </ItemTemplate>

            <EditItemTemplate>

            <asp:TextBox ID="txtCountry" runat="server" Text='<%#Bind("country") %>' MaxLength="20"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtCountry" runat="server" Text="*" ToolTip="Enter country" ControlToValidate="txtCountry"></asp:RequiredFieldValidator>

        

            </EditItemTemplate>

            <FooterTemplate>

            <asp:TextBox ID="txtNewCountry" runat="server" MaxLength="20"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtNewCountry" runat="server" Text="*" ToolTip="Enter country" ControlToValidate="txtNewCountry"></asp:RequiredFieldValidator>

            </FooterTemplate>

            </asp:TemplateField>

 

            <asp:TemplateField>

            <HeaderTemplate>City</HeaderTemplate>

            <ItemTemplate>

            <asp:Label ID = "lblCity" runat="server" Text='<%#Bind("city") %>'></asp:Label>

            </ItemTemplate>

            <EditItemTemplate>

            <asp:TextBox ID="txtCity" runat="server" Text='<%#Bind("city") %>' MaxLength="20"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtCity" runat="server" Text="*" ToolTip="Enter city" ControlToValidate="txtCity"></asp:RequiredFieldValidator>

            </EditItemTemplate>

            <FooterTemplate>

            <asp:TextBox ID="txtNewCity" runat="server" MaxLength="20"></asp:TextBox>

            <asp:RequiredFieldValidator ID="rfvtxtNewCity" runat="server" Text="*" ToolTip="Enter city" ControlToValidate="txtNewCity"></asp:RequiredFieldValidator>

            </FooterTemplate>

            </asp:TemplateField>

 

            <asp:TemplateField>

            <HeaderTemplate>Operation</HeaderTemplate>

            <ItemTemplate>

            <asp:Button ID="btnEdit" runat="server" CommandName="Edit" Text="Edit" />

            <asp:Button ID="btnDelete" runat="server" CommandName="Delete" Text="Delete" CausesValidation="true" OnClientClick="return confirm('Are you sure?')" />

            </ItemTemplate>

            <EditItemTemplate>

            <asp:Button ID="btnUpdate" runat="server" CommandName="Update" Text="Update" />

            <asp:Button ID="btnCancel" runat="server" CommandName="Cancel" Text="Cancel" CausesValidation="false" />

            </EditItemTemplate>

 

            <FooterTemplate>

            <asp:Button ID="btnNewInsert" runat="server" Text="Insert" OnClick="InsertNewRecord"/>

            <asp:Button ID="btnNewCancel" runat="server" Text="Cancel" OnClick="AddNewCancel" CausesValidation="false" />

            </FooterTemplate>

 

           

            </asp:TemplateField>

 

           

            </Columns>

            <EmptyDataTemplate>

                      No record available

                     

            </EmptyDataTemplate>

           

        </asp:GridView>

        </br>

        <asp:Button ID="btnAdd" runat="server" Text="Add New Record" OnClick="AddNewRecord" />

   

    </div>

    </form>

</body>

 

Output:

Insert, Delete, Update in GridView in ASP.Net using C#

Step 5:- Write down following code in “.cspage

 

using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

 

public partial class _Default : System.Web.UI.Page

{  

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            FillGridView();

        }

    }

    /// <summary>

    /// Fill record in gridview

    /// </summary>

    public void FillGridView()

    {

        try

        {

            string cnString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;

            SqlConnection con = new SqlConnection(cnString);

            GlobalClass.adap = new SqlDataAdapter("select * from gridvew", con);

            SqlCommandBuilder bui = new SqlCommandBuilder(GlobalClass.adap);

            GlobalClass.dt = new DataTable();

            GlobalClass.adap.Fill(GlobalClass.dt);

            GridView1.DataSource = GlobalClass.dt;

            GridView1.DataBind();

        }

        catch

        {

          

        }

    }

    protected void editRecord(object sender, GridViewEditEventArgs e)

    {

        GridView1.EditIndex = e.NewEditIndex;

        FillGridView();

    }

    protected void cancelRecord(object sender, GridViewCancelEditEventArgs e)

    {

        GridView1.EditIndex = -1;

        FillGridView();

    }

 

    /// <summary>

    /// New Row Add

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void AddNewRecord(object sender, EventArgs e)

    {

        try

        {

            if (GlobalClass.dt.Rows.Count > 0)

            {

                GridView1.EditIndex = -1;

                GridView1.ShowFooter = true;

                FillGridView();

            }

            else

            {       

                GridView1.ShowFooter = true;

                DataRow dr = GlobalClass.dt.NewRow();

                dr[1] = "0";

                dr[2] = 0;

                dr[3] = 0;

                dr[4] = "0";

                dr[5] = "0";

                GlobalClass.dt.Rows.Add(dr);

                GridView1.DataSource = GlobalClass.dt;

                GridView1.DataBind();

                GridView1.Rows[0].Visible = false;

            }

        }

        catch

        {

 

        }

    }

 

    /// <summary>

    /// New Record Cancel

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void AddNewCancel(object sender, EventArgs e)

    {

        GridView1.ShowFooter = false;

        FillGridView();

    }

 

    /// <summary>

    /// Insert New Record

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void InsertNewRecord(object sender, EventArgs e)

    {

        try

        {

            string strName = GlobalClass.dt.Rows[0]["name"].ToString();

            if (strName == "0")

            {

                GlobalClass.dt.Rows[0].Delete();

                GlobalClass.adap.Update(GlobalClass.dt);

            }

           

                TextBox txtName = GridView1.FooterRow.FindControl("txtNewName") as TextBox;

                TextBox txtAge = GridView1.FooterRow.FindControl("txtNewAge") as TextBox;

                TextBox txtSalary = GridView1.FooterRow.FindControl("txtNewSalary") as TextBox;

                TextBox txtCountry = GridView1.FooterRow.FindControl("txtNewCountry") as TextBox;

                TextBox txtCity = GridView1.FooterRow.FindControl("txtNewCity") as TextBox;

 

                DataRow dr = GlobalClass.dt.NewRow();

                dr["name"] = txtName.Text.Trim();

                dr["age"] = txtAge.Text.Trim();

                dr["salary"] = txtSalary.Text.Trim();

                dr["country"] = txtCountry.Text.Trim();

                dr["city"] = txtCity.Text.Trim();

                GlobalClass.dt.Rows.Add(dr);

                GlobalClass.adap.Update(GlobalClass.dt);

                GridView1.ShowFooter = false;

                FillGridView();

          

        }

        catch

        {

 

        }

 

    }

    /// <summary>

    /// Record Updation

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void updateRecord(object sender, GridViewUpdateEventArgs e)

    {

        try

        {

            TextBox txtName = GridView1.Rows[e.RowIndex].FindControl("txtName") as TextBox;

            TextBox txtAge = GridView1.Rows[e.RowIndex].FindControl("txtAge") as TextBox;

            TextBox txtSalary = GridView1.Rows[e.RowIndex].FindControl("txtSalary") as TextBox;

            TextBox txtCountry = GridView1.Rows[e.RowIndex].FindControl("txtCountry") as TextBox;

            TextBox txtCity = GridView1.Rows[e.RowIndex].FindControl("txtCity") as TextBox;

 

            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["name"] = txtName.Text.Trim();

            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["age"] = Convert.ToInt32(txtAge.Text.Trim());

            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["salary"] = Convert.ToInt32(txtSalary.Text.Trim());

            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["country"] = txtCountry.Text.Trim();

            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex]["city"] = txtCity.Text.Trim();

            GlobalClass.adap.Update(GlobalClass.dt);

            GridView1.EditIndex = -1;

            FillGridView();

        }

        catch

        {

          

        }

    }

 

    /// <summary>

    /// Record Deletion

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void RowDeleting(object sender, GridViewDeleteEventArgs e)

    {

        try

        {

            GlobalClass.dt.Rows[GridView1.Rows[e.RowIndex].RowIndex].Delete();

            GlobalClass.adap.Update(GlobalClass.dt);

            FillGridView();

        }

        catch

        {

 

        }

    }

}

 

Step 6:- Now, execute the web application and click on button ‘Add New Record’ for adding new record in GridView.

Insert, Delete, Update in GridView in ASP.Net using C#Insert, Delete, Update in GridView in ASP.Net using C#

Step 7:- Fill all TextBox and click button “Insert” and see output

Insert, Delete, Update in GridView in ASP.Net using C#

Note:- Id are generated automatic for every new record

Step 8:- For update records click button “Edit”  and change TextBox Data. For example in place of “Avadhesh” I write “Avadhesh Patel” then click button “Update”. Through button “cancel” we return previous position.

Insert, Delete, Update in GridView in ASP.Net using C#

 

Insert, Delete, Update in GridView in ASP.Net using C#

Step 9:- Through button “Delete” we can delete record form GridView. Before deleting record one Pop up Box conforms for action.

Insert, Delete, Update in GridView in ASP.Net using C#

Report Abuse Form
Reason:    
 


Please help
by toan buivan 11/22/2012 10:00:46 AM
Sir i'm is a newbie studing asp.net and i dont know where is the global class  GlobalClass in your post to understand

(sorry my English is bad)

Report Abuse

global class
by AVADHESH PATEL 11/24/2012 12:06:29 AM
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class GlobalClass
{
    public static int autoId;
    public static SqlDataAdapter adap;
    public static DataTable dt;
}
Report Abuse

While click on Add New Record,i m getting this type of Error message--Object reference not set to an instance of an object.kindly follow the below code and tell me where exactly i need to declare the Global Class
by kamal pradhan 12/28/2012 12:06:48 PM
Dear Sir,
  Kindly help me,where exactly i need to declare Global Class and while click on Add New Record,its throwing Error--Object reference not set to an instance of an object.please follow the below code,if any solution u get,kindly mail me in this below email id- kamalsekhar@hotmail.com.sp i will be greateful to u.

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

public class GlobalClass
        {
            public static int autoId;
            public static SqlDataAdapter adap;
            public static DataTable dt;
        }

namespace GridViewExample
{
    public partial class GridviewEx : System.Web.UI.Page
    {
                protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillGridView();
            }
        }
------------------------------------------------------------------
protected void AddNewRecord(object sender, EventArgs e)
        {
            try
            {
                if (GlobalClass.dt.Rows.Count > 0)
                {
                    GridView1.EditIndex = -1;
                    GridView1.ShowFooter = true;
                    FillGridView();
                }
                else
                {
                    GridView1.ShowFooter = true;
                    DataRow dr = GlobalClass.dt.NewRow();
                    dr[1] = "0";
                    dr[2] = 0;
                    dr[3] = 0;
                    dr[4] = "0";
                    dr[5] = "0";
                    GlobalClass.dt.Rows.Add(dr);
                    GridView1.DataSource = GlobalClass.dt;
                    GridView1.DataBind();
                    GridView1.Rows[0].Visible = false;

                }

            }
            catch(Exception ex)
            {

            }
        }
Report Abuse

Re, Insert, Delete, Update in GridView in ASP.Net using C#
by AVADHESH PATEL 1/5/2013 12:15:28 AM
Hi Kamal Pradhan

You can create GlobalClass in App_Code folder. Add one cs file and set that name GlobalClass.cs

and write below code.

using System.Data;
using System.Data.SqlClient;

public class GlobalClass
{
    public static int autoId;
    public static SqlDataAdapter adap;
    public static DataTable dt;
}
Report Abuse

app_code folder is not there in visual studio 2008
by Feby Raju 1/5/2013 2:56:31 AM
sir, I couldn't find the app_code folder,. also i tried to add it one. but its not there in the list.
do app_globalresource work????
pls help
Report Abuse
Title :
Comment :
Text ColorBackground Color
BoldItalicUnderline
LeftCenterRightJustify
Ordered ListBulleted List
IndentOutdent
Horizontal Rule
SubscriptSuperscript
HyperlinkImage
Design ModeDesign
View HtmlHtml
     
 
Latest Article by AVADHESH PATELRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Latest BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Top Viewed ArticlesRSS Feed
    
    
    
    
    
    
    
    
    
    
Top Viewed BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
Latest Interview QuestionsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Total Online Users: 7004
Advertisement
MindStick DataConver
Advertise with Us
  
Copyright © 2009 - 2013MindStick. All Rights Reserved.