Click here to Skip to main content
15,445,479 members
Articles / Programming Languages / C#
Posted 23 Sep 2011

Tagged as



edit, Update, Cancel, Delete rows in Gridview(using MS Access DB)

Rate me:
Please Sign up or sign in to vote.
3.67/5 (3 votes)
23 Sep 2011CPOL
Grid Functionalities
Hi, I will show you how to edit, Update, Cancel the update, delete the rows of a gridview(using MS Access DB). Here I have a column by name Percentage where I will restrict the user from entering the alphabets and enable him to enter only percentage values.

The code is all self explanatory.

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Data.OleDb;

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

    //SqlConnection conn; 
    OleDbConnection conn;
    protected void Page_Load(object sender, EventArgs e)
        // for sql db put your connection string here
        conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath
        if(!IsPostBack )  

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

     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
         GridView1.EditIndex = -1;  

     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
         GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
         Label lbl = (Label)row.FindControl("lblid");  
         TextBox textname = (TextBox)row.FindControl("textbox1");  
         TextBox textmarks = (TextBox)row.FindControl("textbox2");  
         GridView1.EditIndex = -1;  
         OleDbCommand cmd = new OleDbCommand("update emp set marks=" + textmarks.Text + " , Username='" + textname.Text + "' where rowid=" + lbl.Text + "", conn);
         //SqlCommand cmd = new SqlCommand("update emp set marks=" + textmarks.Text + " , name='" + textname.Text + "' where rowid=" + lbl.Text + "", conn);  

     public void bind()  
         OleDbDataAdapter da = new OleDbDataAdapter("select * from emp", conn);
         //SqlDataAdapter da = new SqlDataAdapter("select * from emp", conn);  
         DataSet ds = new DataSet();  
         GridView1.DataSource = ds.Tables[0];  

     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
         GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];  
         Label lbldeleteID = (Label)row.FindControl("lblid");  
         OleDbCommand cmd = new OleDbCommand("delete from emp where rowid=" + lbldeleteID.Text + "", conn);
         //SqlCommand cmd = new SqlCommand("delete  emp where rowid=" + lbldeleteID.Text + "", conn);  

     protected void GridView1_PageIndexChanging1(object sender, GridViewPageEventArgs e)

         GridView1.PageIndex = e.NewPageIndex;
         GridView1.EditIndex = -1;

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head  runat="server">
    <title>Edit,Delete,Update the Grid</title>
    <script type="text/javascript">
 function ispercentage(obj, e, allowDecimal, allowNegative) 
   var key;
   var isCtrl = false;
   var keychar;
   var reg;
   if (window.event) 
     key = e.keyCode;
     isCtrl = window.event.ctrlKey
   else if (e.which)
     key = e.which;
     isCtrl = e.ctrlKey;
   if (isNaN(key)) return true;
   keychar = String.fromCharCode(key);
   // check for backspace or delete, or if Ctrl was pressed
   if (key == 8 || isCtrl)
     return true;
   ctemp = obj.value;
   var index = ctemp.indexOf(".");
   var length = ctemp.length;
   ctemp = ctemp.substring(index, length);
   if (index < 0 && length > 1 && keychar != '.' && keychar != '0')
     return false;
   if (ctemp.length > 2)
     return false;
   if (keychar == '0' && length >= 2 && keychar != '.' && ctemp != '10') {
     return false;
   reg = /\d/;
   var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
   var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
   return isFirstN || isFirstD || reg.test(keychar);

    <form id="form1"  runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Style="z-index: 100;
            left: 177px; position: absolute; top: 118px; width: 315px;" AllowPaging="true"
            AllowSorting="True" AutoGenerateEditButton="True" OnRowEditing="GridView1_RowEditing"
            OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdating="GridView1_RowUpdating"
            OnRowDeleting="GridView1_RowDeleting" BackColor="#FF8080" BorderColor="SaddleBrown"
            BorderStyle="None" CellPadding="4" ForeColor="#333333" GridLines="None" PageSize="5"
                <asp:TemplateField HeaderText="IDNO">
                        <asp:Label ID="lblid" runat="server" Text='<%#Eval("rowid") %>'></itemtemplate>
                <asp:TemplateField HeaderText="Name">
                        <asp:TextBox ID="textbox1" runat="server" Text='<%#Eval("Username") %>' CausesValidation="true">
                        <asp:RequiredFieldValidator ID="namevalidate" runat="server" Text="Please enter Name"
                <asp:TemplateField HeaderText="Percentage">
                        <%#Eval("marks") %>
                        <asp:TextBox ID="textbox2" runat="server" Text='<%#Eval("marks") %>' CausesValidation="true"
                            onkeypress="return ispercentage(this, event, true, false);" MaxLength="5">
                        <asp:RequiredFieldValidator ID="marksValidate" runat="server" Text="Please enter marks"
                        <%-- <asp:RangeValidator MinimumValue="0" MaximumValue="100" ID="marksrangeValidate" runat="server" ControlToValidate="textbox2" Text="Enter with in 0 and 100">--%>
            <footerstyle backcolor="#990000" font-bold="True" forecolor="White" />
            <rowstyle backcolor="#FFFBD6" forecolor="#333333" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
            <pagerstyle backcolor="#FFCC66" forecolor="#333333" horizontalalign="Center" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <alternatingrowstyle backcolor="White" />

Here I have a script called isPercentage which allows only numbers to be entered in the edit textbox. Rest of the code is all self explanatory. I have coded it using MS Access DB and the same using SQL has been provided in the comment lines. Provide the intial connection string and then proceed with the things.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer Wipro Technologies
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

GeneralThis is for beginners not for the professionals. And i didn'... Pin
lperumb25-Sep-11 20:50
Memberlperumb25-Sep-11 20:50 
GeneralReason for my vote of 1 Its good for beginers.... Pin
Sushil Kumar Purohit25-Sep-11 19:09
MemberSushil Kumar Purohit25-Sep-11 19:09 
GeneralRe: Reason for my vote of 1Its good for beginers.... Pin
lperumb21-Mar-12 0:27
Memberlperumb21-Mar-12 0:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.