Skip to main content

Insert, Edit, Update, Delete in Asp.Net Gridview

Introduction:
In this article I will explain how to Insert, Edit, Update, Delete in Gridview in Asp.Net using C#.

Description:
First I will write code to Insert data into Gridview then I will perform Edit, Update and Delete operations on it. For achieving all these functionalities I have used following Gridview commands, they are:

  • onrowediting
  • onrowupdating
  • onrowcancelingedit
  • onPageIndexChanging
Below is the code for aspx page:
<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">
function ConfirmationBox(username) {

var result = confirm('Are you sure you want to delete '+username+' Details?' );
if (result) {

return true;
}
else {
return false;
}
}
</script>
</head>
<body>
    <form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId,UserName" runat="server"
        AutoGenerateColumns="false" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
        onrowcancelingedit="gvDetails_RowCancelingEdit"
        onrowdeleting="gvDetails_RowDeleting" onrowediting="gvDetails_RowEditing"
        onrowupdating="gvDetails_RowUpdating"
        onrowcommand="gvDetails_RowCommand">
    
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server"ImageUrl="~/Images/update.jpg" ToolTip="Update" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel"ImageUrl="~/Images/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />

</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server"ImageUrl="~/Images/Edit.jpg" ToolTip="Edit" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnDelete" CommandName="Delete" Text="Edit"runat="server" ImageUrl="~/Images/delete.jpg" ToolTip="Delete" Height="20px"Width="20px" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server"ImageUrl="~/Images/AddNewitem.jpg" CommandName="AddNew" Width="30px"Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />

</FooterTemplate>
 </asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<EditItemTemplate>
<asp:Label ID="lbleditusr" runat="server" Text='<%#Eval("Username") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblitemUsr" runat="server" Text='<%#Eval("UserName") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrusrname" runat="server"/>
<asp:RequiredFieldValidator ID="rfvusername" runat="server" ControlToValidate="txtftrusrname" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
 <asp:TemplateField HeaderText="City">
 <EditItemTemplate>
 <asp:TextBox ID="txtcity" runat="server" Text='<%#Eval("City") %>'/>
 </EditItemTemplate>
 <ItemTemplate>
 <asp:Label ID="lblcity" runat="server" Text='<%#Eval("City") %>'/>
 </ItemTemplate>
 <FooterTemplate>
 <asp:TextBox ID="txtftrcity" runat="server"/>
 <asp:RequiredFieldValidator ID="rfvcity" runat="server" ControlToValidate="txtftrcity" Text="*" ValidationGroup="validaiton"/>
 </FooterTemplate>
 </asp:TemplateField>
 <asp:TemplateField HeaderText="Designation">
 <EditItemTemplate>
 <asp:TextBox ID="txtstate" runat="server" Text='<%#Eval("Designation") %>'/>
 </EditItemTemplate>
 <ItemTemplate>
 <asp:Label ID="lblstate" runat="server" Text='<%#Eval("Designation") %>'/>
 </ItemTemplate>
 <FooterTemplate>
 <asp:TextBox ID="txtftrDesignation" runat="server"/>
  <asp:RequiredFieldValidator ID="rfvdesignation" runat="server" ControlToValidate="txtftrDesignation" Text="*" ValidationGroup="validaiton"/>
 </FooterTemplate>
 </asp:TemplateField>
 </Columns>
</asp:GridView>

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



Code for aspx.cs page is:

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;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    private SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindEmployeeDetails();
        }
    }
    protected void BindEmployeeDetails()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        if (ds.Tables[0].Rows.Count > 0)
        {
            gvDetails.DataSource = ds;
            gvDetails.DataBind();
        }
        else
        {
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            gvDetails.DataSource = ds;
            gvDetails.DataBind();
            int columncount = gvDetails.Rows[0].Cells.Count;
            gvDetails.Rows[0].Cells.Clear();
            gvDetails.Rows[0].Cells.Add(new TableCell());
            gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
            gvDetails.Rows[0].Cells[0].Text = "No Records Found";
        }

    }

    protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvDetails.EditIndex = e.NewEditIndex;
        BindEmployeeDetails();
    }

    protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgse)
    {
        int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
        string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
        TextBox txtcity = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtcity");
        TextBox txtDesignation = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtstate");
        con.Open();
        SqlCommand cmd = new SqlCommand("update Employee_Details set City='" + txtcity.Text + "',Designation='" + txtDesignation.Text + "' where UserId=" + userid, con);
        cmd.ExecuteNonQuery();
        con.Close();
        lblresult.ForeColor = Color.Green;
        lblresult.Text = username + " Details Updated successfully";
        gvDetails.EditIndex = -1;
        BindEmployeeDetails();
    }

    protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvDetails.EditIndex = -1;
        BindEmployeeDetails();
    }

    protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgse)
    {
        int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
        string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
        con.Open();
        SqlCommand cmd = new SqlCommand("delete from Employee_Details where UserId=" + userid, con);
        int result = cmd.ExecuteNonQuery();
        con.Close();
        if (result == 1)
        {
            BindEmployeeDetails();
            lblresult.ForeColor = Color.Red;
            lblresult.Text = username + " details deleted successfully";
        }
    }

    protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //getting username from particular row
            string username = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "UserName"));
            //identifying the control in gridview
            ImageButton lnkbtnresult = (ImageButton)e.Row.FindControl("imgbtnDelete");
            //raising javascript confirmationbox whenver user clicks on link button
            if (lnkbtnresult != null)
            {
                lnkbtnresult.Attributes.Add("onclick""javascript:return ConfirmationBox('" + username + "')");
            }

        }
    }

    protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgse)
    {
        if (e.CommandName.Equals("AddNew"))
        {
            TextBox txtUsrname = (TextBox)gvDetails.FooterRow.FindControl("txtftrusrname");
            TextBox txtCity = (TextBox)gvDetails.FooterRow.FindControl("txtftrcity");
            TextBox txtDesgnation = (TextBox)gvDetails.FooterRow.FindControl("txtftrDesignation");
            con.Open();
            SqlCommand cmd =
                new SqlCommand(
                    "insert into Employee_Details(UserName,City,Designation) values('" + txtUsrname.Text + "','" +
                    txtCity.Text + "','" + txtDesgnation.Text + "')", con);
            int result = cmd.ExecuteNonQuery();
            con.Close();
            if (result == 1)
            {
                BindEmployeeDetails();
                lblresult.ForeColor = Color.Green;
                lblresult.Text = txtUsrname.Text + " Details inserted successfully";
            }
            else
            {
                lblresult.ForeColor = Color.Red;
                lblresult.Text = txtUsrname.Text + " Details not inserted";
            }


        }


    }

}




Modify connection string as:

<connectionStrings>
    <add name="dbconnection" connectionString="Data Source=ServerName;Initial Catalog= DatabaseName;Persist Security Info=True;User ID=sa;Password=****"/>
  </connectionStrings>








Comments

Popular posts from this blog

Retrieve Gmail Inbox into Asp.Net using Pop3.

I ntroduction : In this article I will explain how to integrate gmail mail into asp.net using pop3 server. Pop3 Commands: The commands used to retrieve mail from a Pop3 server by an email client are a series of text commands with single line responses from the mail server. The commands and examples used here are defined by   RFC 1939- Post Office Protocol- Version 3. user: User is the first command after the connection is established. To connect, all you have to do is supply your e-mail user id. Example Usage: USER  john.smith PASS: After having supplied your user name, the next command is to supply your e-mail password. Example Usage: PASS  **** STAT: Returns the number of emails in the mailbox and the number of bytes all the emails are taking on the server. Example Usage: STAT Sample Response:  +OK 3 345910   TOP : Takes  two arguments i.e., the sort number of the email on the server and the number of lines of text to...

How to Create ContactUs page using Rich TextBox in Asp.Net

I ntroduction : As we know, ASP.NET lacks a control that we need most,   RichText  editor. If you are trying to create an application or website with Admin Panel or Blog or Forum Website or some such project for Web in ASP.NET platform, we need RichText Editor. To overcome this, we can use many open source JavaScript based editors, like Tiny MCE, FCKEditor, etc. here we are using TinyMCE, which is one of the most popular and Open Source projects. Download the latest version of TinyMCE from  download page , and extract the zip file. Steps: Create a new WebPage  in  VS 2008. Browse the extracted location and go to  ..\tinymce_3.5.6\tinymce\jscripts   folder. Now copy the  tinymce  folder from the above location to your solution in Visual Studio. Step 1: Create a  WebPage  file named  ContactUs.aspx . Paste the code below into  ContactUs.aspx: < html   xmlns ="http:/...