Thursday, 7 March 2013

Gridview Edit Delete and Update in ASP.NET


Websites often display thousands of data in a GridView in ASP.Net. Usually admin can view the registered users on the website, but when an admin wants to edit or delete any fraud or duplicate or damaged data from the table there is a method in GridView to edit, delete and update. See the note section below.

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

<!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 id="Head1" runat="server">
    <title>Untitled Page</title>
    <style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;

}
</style>
<script type="text/javascript">

</script>
</head>
<body>
    <form id="form1" runat="server">
<div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="id"OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"OnRowUpdating="GridView1_RowUpdating">
    <Columns>
        <asp:BoundField DataField="id" HeaderText="S.No." />
        <asp:BoundField DataField="name" HeaderText="Name" />
        <asp:BoundField DataField="address" HeaderText="address" />
        <asp:BoundField DataField="country" HeaderText="Country" />
        <asp:CommandField ShowEditButton="true" />
        <asp:CommandField ShowDeleteButton="true" />
        </Columns>
    </asp:GridView>

    </div>
<div>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</div>
    </form>
</body>
</html>
Design

The design part will look as in the following image:

GridView1.jpg

Code behind
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
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;

public partial class _Default : System.Web.UI.Page
{
    private SqlConnection conn = new SqlConnection("Data Source=REDDYS-PC;Integrated Security=true;Initial Catalog=sample");
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                gvbind();
            }
        }
        protected void gvbind()
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand("Select * from detail", conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            conn.Close();
            if (ds.Tables[0].Rows.Count > 0)
            {
                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
            else
            {
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                GridView1.DataSource = ds;
                GridView1.DataBind();
                int columncount = GridView1.Rows[0].Cells.Count;
                GridView1.Rows[0].Cells.Clear();
                GridView1.Rows[0].Cells.Add(new TableCell());
                GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
                GridView1.Rows[0].Cells[0].Text = "No Records Found";
            }

        }      

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
            Label lbldeleteid = (Label)row.FindControl("lblID");
            conn.Open();
            SqlCommand cmd = new SqlCommand("delete FROM detail where id='"+Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString())+"'", conn);
            cmd.ExecuteNonQuery();
            conn.Close();
            gvbind();

        }
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            gvbind();
        }
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
            GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
            Label lblID = (Label)row.FindControl("lblID");
            //TextBox txtname=(TextBox)gr.cell[].control[];
            TextBox textName = (TextBox)row.Cells[0].Controls[0];
            TextBox textadd = (TextBox)row.Cells[1].Controls[0];
            TextBox textc = (TextBox)row.Cells[2].Controls[0];
            //TextBox textadd = (TextBox)row.FindControl("txtadd");
            //TextBox textc = (TextBox)row.FindControl("txtc");
            GridView1.EditIndex = -1;
            conn.Open();
            //SqlCommand cmd = new SqlCommand("SELECT * FROM detail", conn);
            SqlCommand cmd = new SqlCommand("update detail set name='"+textName.Text+"',address='"+textadd.Text+"',country='"+textc.Text+"'where id='"+userid+"'",conn);
            cmd.ExecuteNonQuery();
            conn.Close();
            gvbind();
            //GridView1.DataBind();
        }
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            gvbind();
        }
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            gvbind();
        }
}
Save all or press "Ctrl+S" and hit "F5" to run the page, the page will look as in the following image:

GridView2.jpg

Click on "Edit the GridView", it will display Textboxes in each cell as in the following image:

GridView3.jpg

Difference between Value types & Reference types.


Value types:

* Value types can be created at compile time.
* Stored in stack memory.
* Garbage collector can't access the stack
* value types holds the data directly
* No default values will be stored in value types
* Examples for value types: Predefined datatypes,structures,enums



Reference types:

* Reference types can be created at run time.
* Stored in heap memory
* Garbage collector can access heap
* Reference types holds the data indiredtly
* Reference types holds default value
* Examples for reference types: Classes,objects,Arrays,Indexers,Interfaces