Monday 11 February 2013

ASP.Net: Gridview Edit/Delete/Update | Neha Sharma


Introduction:
                        Most of the time our website display thousands of data in Gridview in ASP.net.Ususally admin can view the registered users on the website, but when an admin want to edit or delete any fraud or duplicate or damaged data from the table a method in Gridview Edit, Delete and update is available.

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 ll look like the below image :


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=NEHASHAMA;Integrated Security=true;Initial Catalog=rp");
        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 ll look like below image :


Click on Edit the GridView it ll display Textboxes in each cell like below image :

Edit the value here and click on Update link, it ll update whole data  or want to remove click on delete link above image shown.


Thanks.
Neha Sharma

29 comments:

  1. I use this code but this is not correct I think something happen with this code.
    Website Design Company in Malaysia | PHP Zend Developer

    ReplyDelete
  2. I also used this code but when i m running this code it is showing:
    Unable to cast object of type 'System.Web.UI.WebControls.DataControlLinkButton' to type 'System.Web.UI.WebControls.TextBox'- In Updating function

    Please help me in this

    ReplyDelete
  3. Thanks for your reply....
    I have marked * in the below .This code is working but update is creating problem.

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

    ReplyDelete
  4. What you have done in design part have you taken LinkButton there?this is creating problem.try to take command event there.

    ReplyDelete
  5. Thanks once again for your reply.... i am sending you my code. Please check and suggest me what will i do because i m new in asp.net programming.
    If u need complete code i can also send u.
    Code:
    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();


    }

    ReplyDelete
  6. I am juz asking did u used Linkbutton there?make compare my design code also with yours

    ReplyDelete
  7. No i did not used any Linkbutton in my design code.

    ReplyDelete
  8. It is showing:- InvalidCastException was unhandled by user-Unable to cast object of type 'System.Web.UI.WebControls.DataControlLinkButton' to type 'System.Web.UI.WebControls.TextBox'.

    As i told u in the above conversation.

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. Hii Neha....actually the code is not showing on your blog. Could u tell me ur public email-id so i can mail u my code.

    ReplyDelete
  11. Please post it on c# corner and let me know the link please.

    ReplyDelete
  12. Check this link: http://www.c-sharpcorner.com/Blogs/11842/how-to-edit-delete-update-or-cancel-record-in-gridview-usi.aspx

    ReplyDelete
  13. Hi,I ll help you using team viewer do you have??If yes wait for some time else please download and install it and let me know when u are ready .

    ReplyDelete
  14. You mean Adobe dreamweaver??? yes Adobe dreamweaver CS5.5 is already installed in my PC.

    ReplyDelete
  15. TeamViewer in not installed. i will install it and let u know.

    ReplyDelete
  16. Hey Neha...i have install it tell me what will i do?

    ReplyDelete
  17. Hey Neha thanku so much for your help.....

    Tell me what will do next?????

    ReplyDelete
  18. Hi Shaily,

    Please mention here problem solved or not ??give review here please.

    ReplyDelete
  19. Hey Neha...My Problem is solved...
    Thanku soo much for your help and support.

    ReplyDelete
  20. Hii Neha...Thanks once again....i just want to ask that how can we add a dialogue box before deleting the record in this code???

    ReplyDelete
  21. Shaily, read my article "Text box validations in asp.net"

    http://nehaprogrammer.blogspot.in/2013/05/aspnet-text-box-validation-part-ii-neha.html

    It ll help you.

    Thanks.

    ReplyDelete
  22. Hi Neha Sharma,
    i have data type mismatch error pls help me

    ReplyDelete

Which Game Engine you should choose | Neha Sharma

Unity3D and Unreal Engine are only 2 Game engine which executes an indispensable position in Game Industry. The choice of the engine must ...