Insert ,update and delete in GridView using WCF Service in
ASP.net
Today we discus about the WCF services
with Insert , Update and Delete with GridView in Asp .net
First we create WCF Services………….
Open new Website in Visual Studio 2010/2012
Select WCF Service (Visual C#)
Now add new item (entity Model)
Select Generate from database and click Next button:-
New create new connection with database(Sql Server 2005/2008)
input server name
use Sql Server authentication
option if user name and password are available orther wise select
Use windows authentication
Select or enter a database name:
enter database name
now click ok button. now click next button
now select table name:-
now click on finish.
we have one interface and one
class name (IService and Service )
Code for IService Interface:-
using System;
using
System.Collections.Generic;
using
System.ComponentModel.DataAnnotations;
using System.Linq;
using
System.Runtime.Serialization;
using
System.ServiceModel;
using
System.ServiceModel.Web;
using System.Text;
[ServiceContract]
public interface IService
{
[OperationContract]
[FaultContract(typeof(OverflowException))]
[FaultContract(typeof(FormatException))]
[FaultContract(typeof(DivideByZeroException))]
List<userdetail> GetData();
[OperationContract]
string insertData(userDetails user);
[OperationContract]
string UpdateData(userDetails user);
[OperationContract]
string DeleteData(userDetails user);
}
[DataContract]
public class userDetails
{
int
mid;
string
mname;
int
mage;
string
memailid;
string
mpass;
string
mph;
[DataMember(Order=1)]
public int id
{
get { return mid; }
set { mid = value; }
}
[DataMember(Order = 2)]
[DataType(DataType.Text)]
public string name
{
get{return mname;}
set { mname = value; }
}
[DataMember(Order = 3)]
public int age
{
get { return mage; }
set { mage = value; }
}
[DataMember(Order = 4)]
[DataType(DataType.EmailAddress)]
public string emailid
{
get { return memailid; }
set { memailid = value; }
}
[DataMember(Order = 5)]
public string pass
{
get { return mpass; }
set { mpass =value ;}
}
[DataMember(Order = 6)]
public string ph
{
get { return mph; }
set { mph = value; }
}
}
Code for Service Class
that implement IService Interface:-
using System;
using
System.Collections.Generic;
using System.Data;
using System.Linq;
using
System.Runtime.Serialization;
using
System.ServiceModel;
using
System.ServiceModel.Web;
using System.Text;
public class Service : IService
{
testEntities te = new testEntities();
string msg = string.Empty;
public List<userdetail> GetData()
{
List<userDetails> dt = new List<userDetails>();
userDetails ud = new userDetails();
var v = te.userdetails.ToList();
return v.ToList();
}
public string insertData(userDetails user)
{
try
{
userdetail ud = new userdetail();
ud.name = user.name;
ud.age = user.age;
ud.emailid = user.emailid;
ud.ph = user.ph;
te.userdetails.Add(ud);
te.SaveChanges();
msg = "Data added
successfully";
return msg;
}
catch (Exception)
{
return "Some Error occured ! ... Please
Contanct Program vendor";
}
}
public string UpdateData(userDetails user)
{
try
{
var v =
te.userdetails.FirstOrDefault(m => m.id == user.id);
if (v != null)
{
v.name = user.name;
v.age = user.age;
v.emailid = user.emailid;
v.ph = user.ph;
te.SaveChanges();
msg ="Data Updated
successfully";
}
return msg;
}
catch (Exception)
{
return "Some Error occured ! ... Please
Contanct Program vendor";
}
}
public string DeleteData(userDetails user)
{
try
{
var v = te.userdetails.FirstOrDefault(m
=> m.id == user.id);
if (v != null)
{
te.userdetails.Remove(v);
te.SaveChanges();
msg = "Data Deleted
Successfully";
}
return msg;
}
catch (Exception ex)
{
return ex.Message;
}
}
}
code for Web.config file
code for Web.config file
<?xml version="1.0"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework
configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,
EntityFramework, Version=5.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Security,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Data.Entity,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<add assembly="System.Data.Entity.Design,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</assemblies>
<buildProviders>
<add extension=".edmx" type="System.Data.Entity.Design.AspNet.EntityDesignerBuildProvider"/>
</buildProviders>
</compilation>
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<services>
<service name ="Service" behaviorConfiguration ="abc">
<endpoint address ="http://localhost:2752/Service.svc" binding ="wsHttpBinding" contract ="IService" ></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name ="abc">
<!-- To avoid disclosing metadata
information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details
in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid
disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during
debugging, set the value below to true.
Set to false before deployment to avoid
disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
<connectionStrings>
<add name="testEntities" connectionString="metadata=res://*/App_Code.Model.csdl|res://*/App_Code.Model.ssdl|res://*/App_Code.Model.msl;provider=System.Data.SqlClient;provider
connection string="data
source=ramulaptop\ramukumar;initial catalog=test;persist security
info=True;user id=sa;password=mysachi;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"/>
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory,
EntityFramework"/>
</entityFramework>
</configuration>
now run the service.svc file from Solution Explorer....
Now create a new
website …..
Add service reference and paste url in address: and click go button
And add service name in Namespace
Then click ok button.
Now design the aspx
page
Code for Aspx:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1
{
width: 100%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div></div>
<div style="width: 600px; padding-left: inherit; padding-right: inherit;">
<table>
<tr>
<td>
<table>
<tr>
<td>Name</td>
<td>
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Age</td>
<td>
<asp:TextBox ID="txtage" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>EmailID</td>
<td>
<asp:TextBox ID="txtEmailid" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<asp:TextBox ID="txtpassword" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td>Phone#</td>
<td>
<asp:TextBox ID="txtph" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:Button ID="btnadd" runat="server" Text="Add
Record"
OnClick="Button1_Click" /></td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Italic="True" Font-Size="15pt" ForeColor="#FF5050"></asp:Label>
</td>
</tr>
</table>
</td>
<td> </td>
<td style="vertical-align: top;">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" Width="900px" CellPadding="3" GridLines="Horizontal" OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" OnRowDataBound="GridView1_RowDataBound" EmptyDataText="Record not
found">
<AlternatingRowStyle BackColor="#F7F7F7" />
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblgrid" runat="server" Text='<%#
Container.DataItemIndex+1 %>'></asp:Label>
<asp:HiddenField ID="hdn" runat="server" Value='<%# Eval("id") %>'></asp:HiddenField>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblgrname" runat="server" Text='<%# Eval("name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtgrname" runat="server" Text='<%# Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email
Id">
<ItemTemplate>
<asp:Label ID="lblgremalid" runat="server" Text='<%# Eval("emailid") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtgremailid" runat="server" Text='<%#Eval ("emailid") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<asp:Label ID="lblgrage" runat="server" Text='<%# Eval("age") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtgrage" runat="server" Text='<%# Eval ("age") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Phone#">
<ItemTemplate>
<asp:Label ID="lblgrph" runat="server" Text='<%# Eval("ph") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtgrph" runat="server" Text='<%# Eval ("ph") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="130px">
<HeaderStyle Width="130px"></HeaderStyle>
<ItemStyle Width="130px" />
<ItemTemplate>
<table class="auto-style1">
<tr>
<td>
<asp:Button ID="btnedit" runat="server" CommandArgument='<%# Eval("id") %>' CommandName="Edit" Text="Edit" />
</td>
<td>
<asp:Button ID="btndelete" runat="server" CommandArgument='<%#Eval("id") %>' CommandName="Delete" Text="Delete" />
</td>
</tr>
</table>
</ItemTemplate>
<EditItemTemplate>
<table class="auto-style1">
<tr>
<td>
<asp:Button ID="btnsave" runat="server" CommandName="Update" Text="Save" />
</td>
<td>
<asp:Button ID="btncancel" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
</tr>
</table>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<SortedAscendingCellStyle BackColor="#F4F4FD" />
<SortedAscendingHeaderStyle BackColor="#5A4C9D" />
<SortedDescendingCellStyle BackColor="#D8D8F0" />
<SortedDescendingHeaderStyle BackColor="#3E3277" />
</asp:GridView>
</td>
</tr>
</table>
<asp:Panel ID="pnlPopup" runat="server" CssClass="modalPopup" Style="display: none">
<div class="body">
Do you want to delete this
record?
</div>
<div class="footer" align="right">
<asp:Button ID="btnYes" runat="server" Text="Yes" CssClass="ui-buttonset" />
<asp:Button ID="btnNo" runat="server" Text="No" />
</div>
</asp:Panel>
</div>
</form>
</body>
</html>
Code for Aspx.cs
using System;
using
System.Collections.Generic;
using System.Linq;
using
System.ServiceModel;
using System.Web;
using System.Web.UI;
using
System.Web.UI.WebControls;
using ServiceReference1;
public partial class _Default : System.Web.UI.Page
{
ServiceClient sc = new ServiceClient();
userDetails ud = new userDetails();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadGridData();
}
}
protected void
GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
loadGridData();
}
public void loadGridData()
{
try
{
GridView1.DataSource =
sc.GetData();
GridView1.DataBind();
}
catch (FaultException<OverflowException> ex)
{
Label1.BackColor = System.Drawing.Color.Gray;
Label1.Text = ex.Message;
}
catch (FaultException<DivideByZeroException> ex)
{
Label1.BackColor = System.Drawing.Color.Blue;
Label1.Text = ex.Message;
}
catch (FaultException<FormatException> ex)
{
Label1.BackColor = System.Drawing.Color.Red;
Label1.Text = ex.Message;
}
catch (ObjectDisposedException ex)
{
Label1.Text = "Object
disposed";
}
catch (CommunicationException ex)
{
Label1.Text = "communication
exception";
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
protected void
GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
loadGridData();
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
userDetails userdata = new userDetails();
userdata.name = txtname.Text;
userdata.age = int.Parse(txtage.Text);
userdata.emailid = txtEmailid.Text;
userdata.pass = txtpassword.Text;
userdata.ph = txtph.Text;
Label1.Text =
sc.insertData(userdata);
GridView1.Caption = Label1.Text;
GridView1.CaptionAlign = TableCaptionAlign.Bottom;
loadGridData();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
protected void
GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
userDetails ud = new userDetails();
HiddenField hdnid =
GridView1.Rows[e.RowIndex].FindControl("hdn") as HiddenField;
TextBox tname =
GridView1.Rows[e.RowIndex].FindControl("txtgrname") as TextBox;
TextBox temail =
GridView1.Rows[e.RowIndex].FindControl("txtgremailid") as TextBox;
TextBox tage =
GridView1.Rows[e.RowIndex].FindControl("txtgrage") as TextBox;
TextBox tphone =
GridView1.Rows[e.RowIndex].FindControl("txtgrph") as TextBox;
ud.id = int.Parse(hdnid.Value);
ud.name = tname.Text;
ud.emailid = temail.Text;
ud.ph = tphone.Text;
ud.age = int.Parse(tage.Text);
Label1.Text = sc.UpdateData(ud);
GridView1.EditIndex = -1;
loadGridData();
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "","
<script> alert('" +Label1.Text+"')" , true);
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
protected void
GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
userDetails ud = new userDetails();
Label l1 =
GridView1.Rows[e.RowIndex].FindControl("lblgrid") as Label;
HiddenField hdnid =
GridView1.Rows[e.RowIndex].FindControl("hdn") as HiddenField;
ud.id = int.Parse(hdnid.Value);
Label1.Text = sc.DeleteData(ud);
loadGridData();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
protected void
GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btndel = e.Row.FindControl("btndelete") as Button;
if (btndel != null &&
btndel.CommandName == "Delete")
// Add delete confirmation
btndel.OnClientClick = "if
(!confirm('Are you sure " +
"you want to
delete this record?')) return false;";
}
}
}
0 comments:
Post a Comment