CRUD (Create ,Read,Update,Delete)
in Grid View with Entity Framework
}
//
execute this query for in
Sql Server 2008 ………..
//create table StateName …………………………..
create table
StateName (SrNo int
,StateCode nvarchar(50) primary key ,StateName nvarchar(50) unique)
This source code for
StateDetails.aspx
<%@ Page Title="" Language="C#"
MasterPageFile="~/Admin.Master"
AutoEventWireup="true"
CodeBehind="StateDetails.aspx.cs"
Inherits="MyRealEstate.StateDetails"
%>
<asp:Content ID="Content1"
ContentPlaceHolderID="head"
runat="server">
<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>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}
</style>
</asp:Content>
<asp:Content ID="Content2"
ContentPlaceHolderID="ContentPlaceHolder1"
runat="server">
<table width="100%">
<tr><td><center><font color="maroon"
><b><i>State Details</i></b></font></center></td></tr>
<tr><td>
<center>
<asp:GridView ID="GridView1"
runat="server"
AutoGenerateColumns="False"
onrowcancelingedit="GridView1_RowCancelingEdit" ShowFooter="True"
onrowcommand="GridView1_RowCommand" onrowediting="GridView1_RowEditing"
AllowPaging="True" PageSize="5"
DataKeyNames="SrNo,StateCode"
onpageindexchanging="GridView1_PageIndexChanging"
onrowdeleting="GridView1_RowDeleting"
onrowdatabound="GridView1_RowDataBound" onrowupdating="GridView1_RowUpdating"
EmptyDataText="no any
state" ToolTip="State Details"
>
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate"
runat="server"
Height="31px"
ImageUrl="~/Images/GridView/Update.jpg" CommandName="Update" ToolTip="Update" Width="31px" />
<asp:ImageButton ID="imgbtnCancel"
runat="server"
Height="31px"
ImageUrl="~/Images/GridView/Cancel.jpg" CommandName="Cancel"
ToolTip="Cancel"
Width="31px"
/>
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAddNew"
runat="server"
CommandName="AddNewItem"
ImageUrl="~/Images/GridView/AddNewitem.jpg" Height="32px"
ToolTip="Add new User" Width="39px" ValidationGroup="group1"
/>
</FooterTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" runat="server"
CommandName="Edit"
ImageUrl="~/Images/GridView/Edit.jpg" ToolTip="Edit" Height="31px" Width="31px" />
 
<asp:ImageButton ID="imgbtnDelete"
runat="server" CommandName="Delete" ImageUrl="~/Images/GridView/delete.jpg" Height="31px"
ToolTip="Delete"
Width="31px"
/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sr
No">
<EditItemTemplate>
<asp:TextBox ID="txtsrno"
runat="server"
Width="50px"
Text='<%# Eval("SrNo") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtsrno"
runat="server"
Width="50px"
></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv1"
runat="server"
ControlToValidate="txtsrno" ErrorMessage="*"
ForeColor="Red"
ValidationGroup="group1" ToolTip="Please
enter Srno in num.."></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblsrno"
runat="server"
Text='<%# Eval("SrNo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sate
Code">
<EditItemTemplate>
<asp:Label ID="lblstatecode"
runat="server"
Text='<%# Eval("StateCode") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtstatecode"
runat="server"
Width="100px"
></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv2"
runat="server"
ControlToValidate="txtstatecode" ErrorMessage="*"
ForeColor="Red"
SetFocusOnError="True" ToolTip="Please
enter state Code"
ValidationGroup="group1"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblstatecode"
runat="server"
Text='<%# Eval("StateCode") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="State
Name">
<EditItemTemplate>
<asp:TextBox ID="txtstatename"
runat="server"
Text='<%# Eval("StateName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtstatename"
runat="server"
Width="100px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv3"
runat="server"
ControlToValidate="txtstatename" ErrorMessage="*"
ForeColor="Red"
SetFocusOnError="True" ToolTip="please
enter state name"
ValidationGroup="group1"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblstatename"
runat="server"
Text='<%# Eval("StateName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
</EmptyDataTemplate>
</asp:GridView>
</center>
</td></tr>
<tr><td ><center>
<asp:Label ID="lblmessage"
runat="server" Visible="false"
Text=""
></asp:Label>
</center>
</td></tr>
</table>
</asp:Content>
This source code for StateDetails.aspx.cs………………………………..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyRealEstate.Data;
using System.Drawing;
using System.Data;
namespace MyRealEstate
{
public partial class StateDetails
: System.Web.UI.Page
{
RealEstateEntities re = new RealEstateEntities();
protected void Page_Load(object sender, EventArgs
e)
{
if (!IsPostBack)
{
GridViewBind();
}
}
//Code for GridView Binding.................
private void
GridViewBind()
{
var res = (from obj
in re.StateNames
orderby obj.SrNo ascending
select new
{
obj.SrNo,
obj.StateName,
obj.StateCode
}).ToList();
if (res.Count > 0)
{
GridView1.DataSource
= res;
GridView1.DataBind();
}
else
{
//Code for GridView Binding when there in no record ........
res.Add(new
{
SrNo =
0,
StateName
= "",
StateCode
= ""
});
GridView1.DataSource
= res;
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
= "There is
no any State in Table";
}
}
// When you click on Cancel ImageButton it shows Edit,Delete
ImageButton
protected void
GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex
= -1;
GridViewBind();
}
//Code for Add New Record in GridView .........................
protected void
GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "AddNewItem")
{
TextBox txtsrno = (TextBox)GridView1.FooterRow.FindControl("txtsrno");
TextBox txtstatecode = (TextBox)GridView1.FooterRow.FindControl("txtstatecode");
TextBox txtstatename = (TextBox)GridView1.FooterRow.FindControl("txtstatename");
MyRealEstate.Data.StateNames sd = new
Data.StateNames();
sd.SrNo
= Convert.ToInt32(txtsrno.Text);
sd.StateCode
= txtstatecode.Text;
sd.StateName
= txtstatename.Text;
re.StateNames.AddObject(sd);
re.SaveChanges();
GridViewBind();
lblmessage.Visible
= true;
lblmessage.ForeColor
= Color.Green;
lblmessage.Text
= "Add State
Succesfully";
}
}
catch (Exception
ex)
{
lblmessage.Visible
= true;
lblmessage.ForeColor
= Color.Red;
lblmessage.Text
= ex.Message;
}
}
// When you click on Edit Link Image it shows Update,Cancel Image
protected void
GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex
= e.NewEditIndex;
GridViewBind();
}
// this code for
paging frist we
set gridview property allowing pagging =true and page size= 5
protected void
GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex
= e.NewPageIndex;
GridViewBind();
}
//Code for GridView Row Deleting................
protected void
GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
int srno = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["SrNo"].ToString());
string statecode =
GridView1.DataKeys[e.RowIndex].Values["StateCode"].ToString();
var res = (from obj
in re.StateNames where
obj.StateCode == statecode select
obj).FirstOrDefault();
MyRealEstate.Data.StateNames sd = new
Data.StateNames();
re.StateNames.DeleteObject(res);
re.SaveChanges();
GridViewBind();
lblmessage.Visible
= true;
lblmessage.ForeColor
= Color.Green;
lblmessage.Text
= "Delete Sucessfully";
}
catch (Exception
ex)
{
lblmessage.Visible
= true;
lblmessage.ForeColor
= Color.Red;
lblmessage.Text
= ex.Message;
}
}
// when user clicks on
Delete link button raising javascript Confirmationbox
protected void
GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string statecode = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "StateCode"));
ImageButton imgbtndelete = (ImageButton)e.Row.FindControl("imgbtnDelete");
if (imgbtndelete != null)
{
imgbtndelete.Attributes.Add("onclick", "javascript:return
ConfirmationBox('" + statecode + "')");
}
}
}
//Code for GridView Row Updating.................
protected void
GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int srno = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
string statecode =
GridView1.DataKeys[e.RowIndex].Values["StateCode"].ToString();
TextBox txtsrno = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtsrno");
TextBox txtstatename = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtstatename");
var res = (from obj
in re.StateNames
where obj.StateCode == statecode
select obj).FirstOrDefault();
if (res != null)
{
res.SrNo
= Convert.ToInt32(txtsrno.Text);
res.StateName
= txtstatename.Text;
re.SaveChanges();
lblmessage.ForeColor
= Color.Green;
lblmessage.Text
= statecode + " Details Updated
successfully";
GridView1.EditIndex
= -1;
GridViewBind();
}
}
}
Nice 1, but i think the code you have copied here is not complete. DB connectivity part is not there. and the code for RealEstateEntities class is not present.
ReplyDeletepls add the complete code for this Nice example
ReplyDeleteFirst go through this link and then refer my code..............
ReplyDeleteHow to connectivity sql server with entity framework
http://kushonline.blogspot.in/2013/07/connectivity-with-sql-server-with.html
thank you sir!
ReplyDeletegrt wrk ..sir!!!
ReplyDelete