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, Update and Insert operations in a DataGrid: Part II

Edit, Delete, Update and Insert operations in a DataGrid: Part II

The basic operations of DataGrid Like Edit, delete, Update, Insert a record.

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

In the previous article I explained how to edit, delete and update the record in DataGrid. Now I am going to explain how to insert a new record in a DataGrid.

 

This is the aspx code.

 

<%@ 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 Delete Cancel and Insert In DataGrid</title>

</head>

<body>

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

    <div>

          <asp:DataGrid ID="gridedit" runat="server" Width="100px"
          
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" 
          SelectedItemStyle-Width="100px">

               <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-Width="10px" Visible="false">

          <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>

                   

          <br /><br />

          <asp:Button ID="btninsert" runat="server" Text="Click Here to Insert a New record" Width="250px"
         
OnClick="InsertNewRecord_click" /><br /><br />

          <asp:Label ID="lblnewname" runat="server" Width="120px" Text="Enter Name" Visible="false"></asp:Label>

         <asp:TextBox ID="txtnewname" runat="server" Visible="false"></asp:TextBox><br /><br />

         <asp:Label ID="lblF_name" runat="server" Width="120px" Text="Enter Father Name" Visible="false"></asp:Label>

         <asp:TextBox ID="txtF_name" runat="server" Visible="false" ></asp:TextBox>

         <br /><br />

         <asp:Label ID="lblLast_name" runat="server" Width="120px" Text="Enter Last Name" Visible="false"></asp:Label>

         <asp:TextBox ID="txtLast_Nmae" runat="server" Visible="false"></asp:TextBox>

         <br /><br />

         <asp:Label ID="lblcity" runat="server" Text="Enter city" Width="120px" Visible="false"></asp:Label>

         <asp:TextBox ID="txtcity" runat="server" Visible="false"></asp:TextBox>

         <br /><br />

         <asp:Label ID="lblState" runat="server" Width="120px" Text="Enter State Name" Visible="false"></asp:Label>

         <asp:TextBox ID="txtState" runat="server" Visible="false"></asp:TextBox>

         <asp:Button ID="btnnewRecordSubmit" runat="server" Text="Insert" OnClick="Submitnew" Width="100px" 
         Visible="false" />
         

    </div>

    </form>

</body>

</html>

From this aspx code the application will look like as:


Figure 1: Application in Designing State.

I set here the visible property of alll label, textBox and insert button False. All of these wiil visible when I will click  Insert a new record button.

The Source code for this is:

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 order by id Asc";

        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)

    {

        try

        {

            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();

        }

        catch (Exception ex)

        { 

            Response.Write(ex.Message);

        } 

    } 

    // 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();

    } 

    //Link for Insert a new Record in a table

    public void InsertNewRecord_click(object source, System.EventArgs e)

    {

        lblnewname.Visible = true;

        txtnewname.Visible = true;

        lblF_name.Visible = true;

        txtF_name.Visible = true;

        lblLast_name.Visible = true;

        txtLast_Nmae.Visible = true;

        lblcity.Visible = true;

        txtcity.Visible = true;

        lblState.Visible = true;

        txtState.Visible = true;

        btnnewRecordSubmit.Visible = true;

   }

    // Command for insert a new Record 

    public void Submitnew(object source, System.EventArgs e)

    {

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

        cmd.CommandText = "insert into record(name,F_name,l_name,City,State) values(@name,@F_Name,@l_name,@City,@State)";

        cmd.Parameters.Add("@name", SqlDbType.Char).Value = txtnewname.Text;

        cmd.Parameters.Add("@F_Name", SqlDbType.Char).Value = txtF_name.Text;

        cmd.Parameters.Add("@l_name", SqlDbType.Char).Value = txtLast_Nmae.Text;

        cmd.Parameters.Add("@City", SqlDbType.Char).Value = txtcity.Text;

        cmd.Parameters.Add("@State", SqlDbType.Char).Value = txtState.Text;

        cmd.Connection = con;

        cmd.Connection.Open();

        cmd.ExecuteNonQuery();

        cmd.Connection.Close();

        gridedit.EditItemIndex = -1;

        Binddata();

        txtnewname.Text = "";

        txtF_name.Text = "";

        txtLast_Nmae.Text = "";

        txtcity.Text = "";

        txtState.Text = "";

        lblnewname.Visible = false; 

        txtnewname.Visible = false;

        lblF_name.Visible = false;

        txtF_name.Visible = false;

        lblLast_name.Visible = false;

        txtLast_Nmae.Visible = false;

        lblcity.Visible = false;

        txtcity.Visible = false;

        lblState.Visible = false;

        txtState.Visible = false;

        btnnewRecordSubmit.Visible = false;

   }
}

Now when User will run the  project then the window will look like as:

         
Figure 2: In running State Project.


Suppose, if user  wants to insert a new record, then they have to click on "Click Here"  button to insert a new record. Onclick of the button, the new  window will  look like this:



Figure 3: Insert a new Record.

When User click this insert button then the record will insert in the DataGrid.



Figure 4: Record Inserted.
 

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:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Dropdown list And datagrid by NagarjunaReddy On April 27, 2007
How to put dropdown list in data grid control in design mode
Reply | Email | Modify 
Re: Dropdown list And datagrid by Rahul Kumar On April 27, 2007

Hi nagarjuna,

Thanx to visit my article , I will post an article with your need soon.

Reply | Email | Modify 
Re: Dropdown list And datagrid by Rahul Kumar On May 14, 2007

To Put DropDown List in DataGrid You have to use <asp:template column> Inside this you will find <Item template>. Inside this you will find <asp: DropDown List> .

Ok dear by doing this you can use DropDpwn list.

 

Reply | Email | Modify 
Re: Dropdown list And datagrid by satish On July 4, 2007
Reply | Email | Modify 
how to add buttons or other controll's in pockect pc datagrid by sonia On May 10, 2007
pls u hv a solution then sen dme soon
Reply | Email | Modify 
Re: how to add buttons or other controll's in pockect pc datagrid by Rahul Kumar On May 14, 2007

Hi sonia,

Thanx to visit my article.
I will send u ur solution as soon ass possible.

ok

 

Reply | Email | Modify 
How to add button and textbox in datagrid coloumn in .net compact framework by sonia On May 10, 2007
Hi , I m working on PDA aplication ,this is very new to me ,so if anyone knows about "How to add button and textbox in datagrid coloumn in .net compact framework" plz maiolas soon as possible
Reply | Email | Modify 
Very helpful artilce. But... by Chris On September 2, 2007
I get these errors when trying to edit or delete: Edit (after clicking 'Update') "Failed to convert parameter value from a Guid to a Int32. " Del (after clicking) "Specified cast is not valid. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. " Exception Details: System.InvalidCastException: Specified cast is not valid. Source Error: Line 88: { Line 89: con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]); Line 90: int U_ID = (int)gridedit.DataKeys[(int)e.Item.ItemIndex]; Line 91: cmd.CommandText = " Delete from record where id=" + U_ID; Line 92: cmd.Connection = con;
Reply | Email | Modify 
Re: Very helpful artilce. But... by Chris On September 3, 2007

I found the answer,

In the updategrid_UpdateCommand class, the id SqlDbType in my DB is a UniqueIdentifier and yours is an Integer. I just changed the type and it worked great!

cmd.Parameters.Add("@id", SqlDbType.Int).Value = gridedit.DataKeys[e.Item.ItemIndex];

cmd.Parameters.Add("@id", SqlDbType.UniqueIdentifier).Value = gridedit.DataKeys[e.Item.ItemIndex];

Thanks again for a very helpful article.

CG

Reply | Email | Modify 
update button in datagrid by laxman On September 28, 2007
hai raahul nice rticle i have the like requirement here i am explainging i have to show an update button in each row of the datagrid and when ever use click the update button user can able to update the row here i know how to add update button in the data grid but idont know how to write code to function the update button please help me it is little bit urgent and i am a new comer thank u in advance
Reply | Email | Modify 
Any run time project s by vinay On March 14, 2008
hello sir, I vinaykumar visited ur site it is just fantastic i jst got lots of information i am very thankful to you . please can u help me. I need a run time project should be used ASp.net ,ado.net and some understandable c# because i am new to c#. onemore time thank u very much Thankyou with regards vinay email:vinykumarv@gmail.com
Reply | Email | Modify 
Re: Any run time project s by Rahul Kumar On March 19, 2008
Hi Vinay Thanx Dear, Well u told me thta u r new to.NET n u need small Project so Enjoy this small Project http://www.dotnetheaven.com/UploadFile/rahul4_saxena/OnLineAddressBook05212007064752AM/OnLineAddressBook.aspx
Reply | Email | Modify 
Re: Any run time project s by Rahul Kumar On March 19, 2008
Reply | Email | Modify 
Re: Any run time project s by Rahul Kumar On February 23, 2009
Hi VINAY One more small project for u http://www.c-sharpcorner.com/UploadFile/rahul4_saxena/MyCollegeMyFriend12222008111537AM/MyCollegeMyFriend.aspx?ArticleID=dc412f94-5a58-4b25-8473-0238562ea290
Reply | Email | Modify 
nice by raj On June 25, 2009
Good explanation .Thank you 

www.rajmohan.co.nr

Reply | Email | Modify 
delete,insert operation in datagrid by ss On March 14, 2010
hi
how in insert you get id is it auto increment? you dont get it this code have error
Reply | Email | Modify 
Question by ashvin On May 13, 2010
suppose i will update the fields based on the datatype nvarchar. how wil i modify the below code

int U_ID = (int)gridedit.DataKeys[(int)e.Item.ItemIndex];
Reply | Email | Modify 
add row in gridview by vasantha On June 2, 2010
i want new row using gridview only..not in textbox
Reply | Email | Modify 

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