SIGN UP MEMBER LOGIN:    
ARTICLE

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

Posted by Rahul Kumar Saxena Articles | C# Language September 26, 2007
Here in this article I am going to show, how to edit, Delete and update data in a DataGrid.
Reader Level:
Download Files:
 

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.

Login to add your contents and source code to this article
share this article :
post comment
 
Become a Sponsor
PREMIUM SPONSORS
  • 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.
    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.
Become a Sponsor