Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Gauge for SharePoint
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » Visual Web Developer 2005 » Edit, Delete and Update in a DataGrid in Visual Web developer 2005

Edit, Delete and Update in a DataGrid in Visual Web developer 2005

Here in this article I am going to show, how to edit, Delete and update data in a DataGrid.

Author Rank :
Page Views : 41886
Downloads : 538
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
editdatagridinvwd.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

If you are going to use DataGrid then here we need to edit, update, delete data in DataGrid. Suppose in that table which data you are using in DataGrid, there  are so many records that on one page all of the records can not come, then here paging plays an important role to show our data in a manner in DataGrid.

So in this article I am going to show how to edit, delete and update data in DataGrid and paging too.

This is the aspx code 

From Here we can design our web form. We use a DataGrid on webForm. Here we set all the property as we have to perform the operation with in DataGrid.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Edit Update Cancel In DataGrid</title>

</head>

<body>

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

    <div>

       <asp:DataGrid ID="gridedit" runat="server" DataKeyField="id" BorderStyle="Ridge" 

         GridLines="None" BorderWidth="2px" BorderColor="White" BackColor="White" 

         CellPadding="3" CellSpacing="1" AllowSorting="True" PagerStyle-

         HorizontalAlign="Center"  HorizontalAlign="Left" OnEditCommand="editgrid_click"     

         OnCancelCommand="gridcancel_click"    

           OnPageIndexChanged="gridedit_PageIndexChanged"         

          OnUpdateCommand="updategrid_UpdateCommand" Height="267px" PageSize=5

            AllowPaging="true"  

            OnDeleteCommand="gridedit_DeleteCommand" AutoGenerateColumns="false"

              Width="50%">

          

        <FooterStyle ForeColor="Black" BackColor="#C6C3C6"></FooterStyle>

        <HeaderStyle Font-Bold="True" ForeColor="#FFFFFF"

                  BackColor="#A53A6A"></HeaderStyle>

       <FooterStyle BackColor="beige" />

       <PagerStyle Font-Bold="true" Mode=NumericPages Font-Underline="true"/>

 

      <Columns>

 

           <asp:BoundColumn DataField=id HeaderText="ID">

          <ItemStyle BackColor="graytext" />

          <HeaderStyle BackColor="graytext" />

          </asp:BoundColumn>

        

          <asp:BoundColumn DataField=name HeaderText="Name">

          <ItemStyle BackColor=GhostWhite />

          </asp:BoundColumn>

                 

          <asp:BoundColumn DataField=F_name HeaderText="F_Name">

          <ItemStyle BackColor=GhostWhite />

          </asp:BoundColumn>

        

          <asp:BoundColumn DataField=l_name HeaderText="L_Name">

          <ItemStyle BackColor=GhostWhite />

          </asp:BoundColumn>

         

          <asp:BoundColumn DataField=City HeaderText="City">

          <ItemStyle BackColor=GhostWhite />

          </asp:BoundColumn>

         

          <asp:BoundColumn DataField=State HeaderText="State">

          <ItemStyle BackColor=GhostWhite />

          </asp:BoundColumn>

         

          <asp:EditCommandColumn CancelText="Cancel" EditText="Edit" 

                         UpdateText="Update" HeaderText="Edit">

          <ItemStyle BackColor=GhostWhite />

          </asp:EditCommandColumn>

         

          <asp:ButtonColumn CommandName="Delete" HeaderText="Delete" Text="Delete">

          <ItemStyle BackColor=GhostWhite />

          </asp:ButtonColumn>

 

      </Columns>

   </asp:DataGrid>

  </div>

</form>

</body>

</html>
 

With this aspx code our web form will become look  like as:


Figure 1   

 

This is the source code:

 

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

 

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

{

    SqlDataAdapter da;

    DataSet ds = new DataSet();

    SqlConnection con;

    SqlCommand cmd = new SqlCommand(); 

 

protected void Page_Load(object sender, EventArgs e)

{

    if (!Page.IsPostBack)

    {

        Binddata();

    }


// Define the Edit Command

public void editgrid_click(object sender, DataGridCommandEventArgs e)

{

    gridedit.EditItemIndex = e.Item.ItemIndex;

    Binddata();

}

 

// Define the Cancel Command

public void gridcancel_click(object sender, DataGridCommandEventArgs e)

{

    gridedit.EditItemIndex = -1;

    Binddata();

}   

 

//Here we Bind the data

public void Binddata()

{

    con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]);

    cmd.CommandText="select * from record";

    cmd.Connection = con;

    da = new SqlDataAdapter(cmd);

    da.Fill(ds);

    con.Open();

    cmd.ExecuteNonQuery();

    gridedit.DataSource = ds;

    gridedit.DataBind();

    con.Close();

}  

  

//Update Command Defination

protected void updategrid_UpdateCommand(object source, DataGridCommandEventArgs e)

{           

    con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]);

    cmd.CommandText = "Update record set name=@name ,F_name=@F_Name,

                     l_name=@l_name,City=@City,State=@State  where id=@id";

    cmd.Parameters.Add("@name", SqlDbType.Char).Value = ((TextBox)e.Item.Cells

                                         [1].Controls[0]).Text;

    cmd.Parameters.Add("@F_name", SqlDbType.Char).Value = ((TextBox)e.Item.Cells

                                         [2].Controls[0]).Text;

    cmd.Parameters.Add("@l_name", SqlDbType.Char).Value = ((TextBox)e.Item.Cells

                                         [3].Controls[0]).Text;

    cmd.Parameters.Add("@City", SqlDbType.Char).Value = ((TextBox)e.Item.Cells

                                         [4].Controls[0]).Text;

    cmd.Parameters.Add("@State", SqlDbType.Char).Value = ((TextBox)e.Item.Cells

                                         [5].Controls[0]).Text;

    cmd.Parameters.Add("@id", SqlDbType.Int).Value = gridedit.DataKeys

                                         [e.Item.ItemIndex];

    cmd.Connection = con;

    cmd.Connection.Open();

    cmd.ExecuteNonQuery();

    cmd.Connection.Close();

    gridedit.EditItemIndex = -1;

    Binddata();

}

 

// Delete Command Defination

public void gridedit_DeleteCommand(object sender, DataGridCommandEventArgs e)

{

    con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]);

    int U_ID = (int)gridedit.DataKeys[(int)e.Item.ItemIndex];

    cmd.CommandText = " Delete from record where  id=" + U_ID;

    cmd.Connection = con;

    cmd.Connection.Open();

    cmd.ExecuteNonQuery();

    cmd.ExecuteNonQuery();

    cmd.Connection.Close();

    gridedit.EditItemIndex = -1;

    Binddata();

}

 

// For Paging

public void gridedit_PageIndexChanged(object source, DataGridPageChangedEventArgs e)

{

    gridedit.CurrentPageIndex = e.NewPageIndex;

    Binddata();

}

}

  

When we run our project then it will look as:


Figure 2

 

If I click on Edit then it will look like as :

  


Figure 3

 

 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Rahul Kumar Saxena
Rahul shows great interests in working with Microsoft technologies. He specializes in the implementation of DataBase & Graphics. His area of expertise includes: C#, ASP.NET,ADO.NET,Windows Forms & Web Services. He hails from background , Master's in Computer Application. With programming he loves photography, traveling and reading books.
(Talabpur*)
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Gauge for SharePoint
Become a Sponsor
 Comments
Help by Chirag On April 22, 2007
Hello Rahul.. i want to see about insert Code. raply me about insert code..
Reply | Email | Modify 
deleting a row from datagrid by bhaskar On July 19, 2007
hi Rahul, in my application i should delete data when checkbox is checked for respective data.can you help me regarding this thanks bhaskar
Reply | Email | Modify 
Help by Karthik On July 20, 2007
Hello Rahul...I need to know the code if the page exceeds one.....updation is not done if page exceeds one.....
Reply | Email | Modify 
help please by Paulin On October 25, 2007
Hi Rahul, Can u please help me with a vb.net code where in i perform update and delete operations all simultaneuosly in a grid and save all the changes made in a single button click.... That is i donot want separate edit , delete update links on my grid. i have got a single button SAVE at the bottom end of my Grid... All the changes i make to the grid should get saved when i click on this button. (SQLserver 2005 , VB.net)
Reply | Email | Modify 
help please by Paulin On October 25, 2007
Hi Rahul, Can u please help me with a vb.net code where in i perform update and delete operations all simultaneuosly in a grid and save all the changes made in a single button click.... That is i donot want separate edit , delete update links on my grid. i have got a single button SAVE at the bottom end of my Grid... All the changes i make to the grid should get saved when i click on this button. (SQLserver 2005 , VB.net)
Reply | Email | Modify 
unknow words or bugs and finding database by william On October 26, 2007
Overall, I liked your article alot. Where is the script to create a table so it can connect and run? Or did you use access database for data on backend? AppData folder unzips but it is empty also. Can you give us your table or shall a I create one so I can get it to run in the browser? Do you want my code after I make a form which updates based on which row of the grid it clicks on? That would be really good. There are bugs here also. It neither liked the words partial nor WebParts. Are they really a part of your problem? THey are no in the namespace. using System.Web.UI.WebControls.WebParts; public partial class _Default : System.Web.UI.Page
Reply | Email | Modify 
datagrid editing by phani On January 10, 2008
datagrid page is going to server but it is not editing
Reply | Email | Modify 
datagrid editing by phani On January 10, 2008
datagrid page is going to server but it is not editing
Reply | Email | Modify 
recordcount and cancelling the adding of data by vincent On January 22, 2009
hi? can you help me? recordcount and cancelling the adding of data in sqldatasource example.. a codes that can read the how many data are entered and if the data, about 25 records, is already that much. The insertion of data will be cancelled.. pls help me tnx'. you can cnd me the codes in my email.. DAVE_ALVAREZ18@YAHOO.COM.PH i'm using Visual web developer 2005 and a sqldatabase.. tnx a lot
Reply | Email | Modify 
Good Example by Hardik On September 14, 2009
very good and simple example for understanding the datagrid control with edit,update,canel facility
Reply | Email | Modify 
Adding numerical values in cells by aj On March 2, 2011
For example, I have numerical values stored in cells in a column. How do I add those numerical values stored on those cells to get their total and display the total in a textbox ? Tnx
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.