How to Edit, Delete, Update or Cancel Record in GridView using ASP.NET

.aspx Code:

<%@ Page Language="C#" AutoEventWireup="true" Debug ="true" EnableEventValidation ="false" CodeFile="View-Record.aspx.cs" Inherits="View_Record" %>

<!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></title>

</head>

<body>

    <style type="text/css">

        .style3

        {

            width: 130px;

        }

    </style>

</head>

<body bgcolor="White" style="background-image: url('images.jpg')";>

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

    <div align="center">

    <p align="right"><a href="Next-page.aspx">Home</a>&nbsp;&nbsp;&nbsp;<a href="View-Record.aspx">View Record</a>&nbsp;&nbsp;&nbsp;<a href="Search-Page.aspx">Search Record</a>&nbsp;&nbsp;&nbsp;<a href="First-page.aspx">Log Out</a></p>

      </div>

<h1 align="center">Student Request Management System</h1>

<div align="center">

<table align="center"><tr><td width="60%" align="left"> View Record:</td><td class="style3" width="60%" align="left">

      <asp:DropDownList ID="DropDownList1" runat="server" Width="126px"

          onselectedindexchanged="DropDownList1_SelectedIndexChanged">

          <asp:ListItem Text="Pending"></asp:ListItem>

          <asp:ListItem Text="Resolved"></asp:ListItem>

          <asp:ListItem Text="All"></asp:ListItem>

    </asp:DropDownList>

     </td></tr>

   </table>

    </div>

    <p align="center"><asp:Button ID="Button1" runat="server" Text="View"

            onclick="Button1_Click" Height="31px" Width="52px" /> &nbsp;&nbsp;&nbsp;&nbsp;

        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Export to Excel"

            Height="31px" Width="107px" />

    </p><br />

     

    <asp:GridView ID="GridView1" runat="server" BackColor="White"

        BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"

        GridLines="Vertical" AutoGenerateColumns="false" OnRowEditing="GridView1_RowEditing"

        OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting"

        OnRowUpdating="GridView1_RowUpdating" AutoGenerateDeleteButton="True"

        AutoGenerateEditButton="True" DataKeyNames="Roll_No">

        <Columns>

        <asp:BoundField DataField="Student_Name" HeaderText="Student_Name" />

        <asp:BoundField DataField="Roll_No" HeaderText="Roll_No" />

        <asp:BoundField DataField="Contact_No" HeaderText="Contact_No" />

        <asp:BoundField DataField="Date" HeaderText="Date" />

        <asp:BoundField DataField="Request_No" HeaderText="Request_No" />

        <asp:BoundField DataField="Type_of_problem" HeaderText="Type_of_problem" />

        <asp:BoundField DataField="Course" HeaderText="Course" />

        <asp:BoundField DataField="Exam_Type" HeaderText="Exam_Type" />

        <asp:BoundField DataField="College" HeaderText="College" />

        <asp:BoundField DataField="Complaint_Status" HeaderText="Complaint_Status" />

        <asp:BoundField DataField="Remarks" HeaderText="Remarks" />

        <asp:CommandField ShowEditButton="true" />

        <asp:CommandField ShowDeleteButton="true" />

        </Columns>

        <RowStyle BackColor="#EEEEEE" ForeColor="Black" />

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

        <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />

        <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />

        <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />

        <AlternatingRowStyle BackColor="#DCDCDC" />

    </asp:GridView>

    <div><asp:Label ID="lblresult" runat="server"></asp:Label></div>

   

</form>

    </body>

</html>
 
Source Code:

 

using System;

using System.Collections;

using System.Configuration;

using System.Data;

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;

using System.Data.SqlClient;

using System.Globalization;

using System.Xml.Linq;

using System.Text;

using System.IO;

 

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

{

    SqlConnection conn;

    protected void Page_Load(object sender, EventArgs e)

    {

        GridView1.Visible = false;

        conn = new SqlConnection("Initial Catalog=Shaily_db;Data Source=DU-PC;Integrated Security=SSPI");

        if (!Page.IsPostBack)

        {

            GridView1.DataSource = BindData();

            GridView1.DataBind();

        }

        else if (!IsPostBack)

        {

            gvbind();

        }

    }

 

    protected void Button1_Click(object sender, EventArgs e)

    {

        GridView1.Visible = true;

 

        switch (DropDownList1.SelectedIndex)

        {

            case 0: GridviewBind2();

                break;

            case 1: GridviewBind1();

                break;

            case 2: GridviewBind();

                break;

        }

    }

    public void GridviewBind()

    {

        SqlConnection con = new SqlConnection("Initial Catalog=Shaily_db;Data Source=DU-PC;Integrated Security=SSPI");

        con.Open();

        SqlCommand cmd = new SqlCommand("Select * from Student_Comp", con);

        SqlDataReader dr = cmd.ExecuteReader();

        GridView1.DataSource = dr;

        GridView1.DataBind();

        con.Close();

    }

    public void GridviewBind1()

    {

        SqlConnection con = new SqlConnection("Initial Catalog=Shaily_db;Data Source=DU-PC;Integrated Security=SSPI");

        con.Open();

        SqlCommand cmd = new SqlCommand("Select * from Student_Comp where Complaint_Status='Resolved'", con);

        SqlDataReader dr = cmd.ExecuteReader();

        GridView1.DataSource = dr;

        GridView1.DataBind();

        con.Close();

    }

    public void GridviewBind2()

    {

        SqlConnection con = new SqlConnection("Initial Catalog=Shaily_db;Data Source=DU-PC;Integrated Security=SSPI");

        con.Open();

        SqlCommand cmd = new SqlCommand("Select * from Student_Comp where Complaint_Status='Pending'", con);

        SqlDataReader dr = cmd.ExecuteReader();

        GridView1.DataSource = dr;

        GridView1.DataBind();

        con.Close();

    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)

    {

    }

    private string ConnectionString

    {

        get

        {

            return @"Server=localhost;Database=Shaily_db;

        Trusted_Connection=true";

        }

    }

    private DataSet BindData()

    {

        // make the query

        string query = "SELECT * FROM Student_Comp";

        SqlConnection myConnection = new SqlConnection(ConnectionString);

        SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);

        DataSet ds = new DataSet();

        ad.Fill(ds, "Student_Comp");

        return ds;

    }

    protected void Button2_Click(object sender, EventArgs e)

    {

        GridView1.Visible = true;

        Response.Clear();

        Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");

        Response.Charset = "";

 

        // If you want the option to open the Excel file without saving than

        // comment out the line below

        // Response.Cache.SetCacheability(HttpCacheability.NoCache);


        Response.ContentType = "application/vnd.xls";

        System.IO.StringWriter stringWrite = new System.IO.StringWriter();

        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        GridView1.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());

        Response.End();

    }

    public override void VerifyRenderingInServerForm(Control control)

    {

    }

    public void gvbind()

    {

        conn.Open();

        SqlCommand cmd = new SqlCommand("Select * from Student_Comp", 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_RowEditing(object sender, GridViewEditEventArgs e)

    {

        GridView1.Visible = true;

        GridView1.EditIndex = e.NewEditIndex;

        gvbind();

    }

 

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

    {

        GridView1.Visible = true;

        GridView1.EditIndex = -1;

        gvbind();

    }

 

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

    {

        GridView1.Visible = true;

        int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());

        GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];

        Label lblID = (Label)row.FindControl("lblID");

        TextBox Student_Name = (TextBox)row.Cells[0].Controls[0];

        TextBox Roll_No = (TextBox)row.Cells[1].Controls[0];

        TextBox Contact_No = (TextBox)row.Cells[2].Controls[0];

        TextBox Date = (TextBox)row.Cells[3].Controls[0];

        TextBox Request_No = (TextBox)row.Cells[4].Controls[0];

        TextBox Type_of_Problem = (TextBox)row.Cells[5].Controls[0];

        TextBox Course = (TextBox)row.Cells[6].Controls[0];

        TextBox Exam_Type = (TextBox)row.Cells[7].Controls[0];

        TextBox College = (TextBox)row.Cells[8].Controls[0];

        TextBox Complaint_status = (TextBox)row.Cells[9].Controls[0];

        TextBox Remarks = (TextBox)row.Cells[10].Controls[0];

        GridView1.EditIndex = -1;

        conn.Open();

        SqlCommand cmd;

        cmd = new SqlCommand("update Student_Comp set Student_Name='" + Student_Name.Text + "' , Roll_No='" + Roll_No.Text + "' , Contact_No='" + Contact_No.Text + "','" + Date.Text + "', '" + Request_No.Text + "', '" + Type_of_Problem.Text + "', '" + Course.Text + "','" + Exam_Type.Text + "', '" + College.Text + "','" + Complaint_status.Text + "','" + Remarks.Text + "', where Roll_No=" + userid + "", conn);

        cmd.ExecuteNonQuery();

        conn.Close();

        gvbind();

        //GridView1.DataBind();

    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

    {

        GridView1.Visible = true;

        GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];

        Label lbldeleteid = (Label)row.FindControl("lblID");

        conn.Open();

        SqlCommand cmd = new SqlCommand("delete FROM Student_Comp where Roll_No='" + Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString()) + "'", conn);

        cmd.ExecuteNonQuery();

        conn.Close();

        gvbind();

    }

 

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

    {

        GridView1.PageIndex = e.NewPageIndex;

        gvbind();

    }

}