Saturday, 30 August 2014

DetailsView CRUD Operations

Hello friends

In this example, we will learn how to perform “CRUD Operations on Detailsview”

In this example, I am using Employee Table

Table script:
CREATE TABLE tbl_Employee
(
EmpId INT Primary key IDENTITY (100, 1) NOT NULL,
EmpName VARCHAR (50) NOT NULL,
EmpDesig VARCHAR (50) NOT NULL,
EmpSalary MONEY NOT NULL
);



Source Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>DetailsView CRUD Operations</title>
</head>
<body>
<form id="form1" runat="server">
<div align="center">
<asp:DetailsView ID="Detailsview1" runat="server"
OnItemUpdating="Detailsview1_ItemUpdating" AutoGenerateRows="False"
OnPageIndexChanging="Detailsview1_PageIndexChanging" AllowPaging="True"
OnItemDeleting="Detailsview1_ItemDeleting"
OnItemInserting="Detailsview1_ItemInserting"
OnModeChanging="Detailsview1_ModeChanging" DataKeyNames="EmpId"
OnDataBound="Detailsview1_DataBound" CellPadding="4"
ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
<EditRowStyle BackColor="#999999" />
<FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White"
HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Fields>
<asp:BoundField ReadOnly="true" HeaderText="Employee Id"
DataField="EmpId" />
<asp:BoundField HeaderText="Employee Name" DataField="EmpName" />
<asp:BoundField HeaderText="Employee Designation"
DataField="EmpDesig" />
<asp:BoundField HeaderText="Employee Salary" DataField="EmpSalary"
DataFormatString="{0:c}" />
<asp:CommandField ButtonType="Button" ShowEditButton="true"
ShowInsertButton="true" ShowDeleteButton="true"/>
</Fields>
</asp:DetailsView>
</div>
</form>
</body>
</html>



C# Code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
public partial class DetailsViewCRUD : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(@"Data Source=(localdb)\Projects;Initial
Catalog=Ranjeet;Integrated Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
data();
}
void data()
{
string query = "select EmpId,EmpName,EmpDesig,EmpSalary from
tbl_Employee";
SqlDataAdapter da = new SqlDataAdapter(query,con);
DataSet ds = new DataSet();
da.Fill(ds);
Detailsview1.DataSource = ds.Tables[0];
Detailsview1.DataBind();
}
protected void Detailsview1_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
try
{
string Id = e.Keys["EmpId"].ToString();
string txtName = ((TextBox)Detailsview1.Rows[1].Cells[1].Controls[0]).Text.Trim();
string txtDesig =
((TextBox)Detailsview1.Rows[2].Cells[1].Controls[0]).Text.Trim();
string txtSalary =
((TextBox)Detailsview1.Rows[3].Cells[1].Controls[0]).Text.Trim();
string query = string.Format("Update tbl_Employee set
EmpName='{0}',EmpDesig='{1}',EmpSalary='{2}' where EmpId={3}",
txtName, txtDesig, txtSalary, Id);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
Response.Write("<script type='text/javascript'>alert('Record Updated Successfully')</script>");
Detailsview1.ChangeMode(DetailsViewMode.ReadOnly);
data();
}
else
{
Response.Write("<script type='text/javascript'>alert('Something Went Wrong')</script>");
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}
protected void Detailsview1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
{
Detailsview1.PageIndex = e.NewPageIndex;
data();
}
protected void Detailsview1_ItemDeleting(object sender, DetailsViewDeleteEventArgs e)
{
try
{
string Id = e.Keys["EmpId"].ToString();
con.Open();
string query = string.Format("delete from tbl_Employee where EmpId={0}", Id);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
Response.Write("<script type='text/javascript'>alert('Record
Deleted Successfully')</script>");
data();
}
else
{
Response.Write("<script type='text/javascript'>alert('Something Went Wrong')</script>");
}
}
catch (Exception ee)
{
Response.Write(ee.Message);
}
finally
{
con.Close();
}
}
protected void Detailsview1_ModeChanging(object sender, DetailsViewModeEventArgs e)
{
if (e.NewMode == DetailsViewMode.Edit)
{
Detailsview1.ChangeMode(DetailsViewMode.Edit);
data();
}
else if (e.NewMode == DetailsViewMode.Insert)
{
Detailsview1.ChangeMode(DetailsViewMode.Insert);
}
else if (e.NewMode == DetailsViewMode.ReadOnly)
{
Detailsview1.ChangeMode(DetailsViewMode.ReadOnly);
data();
}
}
protected void Detailsview1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
try
{
string txtName = ((TextBox)Detailsview1.Rows[1].Cells[1].Controls[0]).Text.Trim();
string txtDesig = ((TextBox)Detailsview1.Rows[2].Cells[1].Controls[0]).Text.Trim();
string txtSalary = ((TextBox)Detailsview1.Rows[3].Cells[1].Controls[0]).Text.Trim();
string query =string.Format("insert into tbl_Employee
values('{0}','{1}','{2}')",txtName,txtDesig,txtSalary);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
Response.Write("<script type='text/javascript'>alert('Record Inserted Successfully')</script>");
Detailsview1.ChangeMode(DetailsViewMode.ReadOnly);
data();
}
else
{
Response.Write("<script type='text/javascript'>alert('Something Went Wrong')</script>");
}
}
catch (Exception ee)
{
Response.Write(ee.Message);
}
finally
{
con.Close();
}
}
protected void Detailsview1_DataBound(object sender, EventArgs e)
{
if (Detailsview1.CurrentMode == DetailsViewMode.Insert)
((TextBox)Detailsview1.Rows[0].Cells[1].Controls[0]).Enabled = false;
}
}
}




Detailsview1_DataBound : In this event when the details view is in 

Insert mode then I'm making EmpId textbox as disable this is why because 

in database i made EmpId column as identity means autoincrement. 

therefore there is no need to give Empid database will automatically get 

it so sending empid is useless.


Detailsview in Readonly Mode:



Detailsview in Edit Mode :


DetailsView in Insert Mode:



If you have any queries regarding this example or Detailsview control post ur comment or send mail to

ranjeetpatil4545@gmail.com


Thank You