Real-Time CRUD Operations In GridView Using WCF In ASP.NET

Performing CRUD Operations in GridView in real-time scenarios using WCF in ASP.NET.

Introduction

WCF refers to Windows Communication Foundation and is a part of .NET 3.0 Framework, a product developed by Microsoft.

To get more details, visit my blog.

http://www.c-sharpcorner.com/blogs/key-notes-to-wcf


Description

We will be going through the following steps.
  • Create a WCF service.
  • Using WCF service in your ASP.Net application.
  • Bind a GridView using the WCF Service.
  • CRUD operations on the GridView using the WCF service in ASP.NET.
  • Textbox Validation using JavaScript.
Steps to be followed
 
Step1

Create two tables, as mentioned below.

Scripts
  1. CREATE TABLE [dbo].[Mas_Employee](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [varchar](50) NOT NULL,  
  4.     [Salary] [varchar](50) NOT NULL,  
  5.     [DeptId] [intNOT NULL,  
  6.     [Status] [intNULL,  
  7.  CONSTRAINT [PK_Mas_Employee] PRIMARY KEY CLUSTERED   
  8. (  
  9.     [Id] ASC  
  10. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  11. ON [PRIMARY]  
  12. GO  
  13.   
  14.   
  15. CREATE TABLE [dbo].[Mas_Department](  
  16.     [DeptId] [int] IDENTITY(1,1) NOT NULL,  
  17.     [DeptName] [varchar](50) NOT NULL,  
  18.     [Status] [intNULL,  
  19.  CONSTRAINT [PK_Mas_Department] PRIMARY KEY CLUSTERED   
  20. (  
  21.     [DeptId] ASC  
  22. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  23. ON [PRIMARY]  
  24. GO 
Step2

Enter dummy data in Mas_Department table. That will be needed during inner join, with first table to fetch records.
  1. SET IDENTITY_INSERT [dbo].[Mas_Department] ON   
  2.   
  3. GO  
  4. INSERT [dbo].[Mas_Department] ([DeptId], [DeptName], [Status]) VALUES (1, N'IT', 1)  
  5. GO  
  6. INSERT [dbo].[Mas_Department] ([DeptId], [DeptName], [Status]) VALUES (2, N'HR', 1)  
  7. GO  
  8. INSERT [dbo].[Mas_Department] ([DeptId], [DeptName], [Status]) VALUES (3, N'ACCOUNTS', 1)  
  9. GO  
  10. SET IDENTITY_INSERT [dbo].[Mas_Department] OFF  
  11. GO 
Step3

Create list of procedures to perform operations. 
  1. IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'USP_Emp_Insert')  
  2.     DROP PROCEDURE USP_Emp_Insert  
  3. GO  
  4.   
  5. -- =============================================  
  6. -- Author:Satyaprakash Samantaray  
  7. -- Opearion : To Insert emplyee details  
  8. -- =============================================  
  9.   
  10.  Create Procedure [dbo].[USP_Emp_Insert]    
  11.     @Name varchar(50),    
  12.     @Salary int,    
  13.     @DeptId int    
  14.     AS    
  15.     Begin    
  16.     Insert into Mas_Employee    
  17.     (Name,Salary,DeptId) Values    
  18.     (@Name,@Salary,@DeptId)    
  19.     End     
  20. GO  
  21.   
  22. ----------------------------------------------------------------------------------------------------------------  
  23.   
  24. IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'USP_Emp_Update')  
  25.     DROP PROCEDURE USP_Emp_Update  
  26. GO  
  27.   
  28. -- =============================================  
  29. -- Author:Satyaprakash Samantaray  
  30. -- Opearion : To update the emplyee details  
  31. -- =============================================  
  32.   
  33. Create Procedure [dbo].[USP_Emp_Update]    
  34.     @Id int,    
  35.     @Name varchar(50),    
  36.     @Salary int,    
  37.     @DeptId int    
  38.     AS    
  39.     Begin    
  40.     update Mas_Employee Set    
  41.     Name=@Name,    
  42.     Salary=@Salary,    
  43.     DeptId=@DeptId    
  44.     where Id=@Id    
  45.     End   
  46. GO  
  47.   
  48. ----------------------------------------------------------------------------------------------------------------  
  49.   
  50. IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'USP_Emp_Delete')  
  51.     DROP PROCEDURE USP_Emp_Delete  
  52. GO  
  53.   
  54. -- =============================================  
  55. -- Author:Satyaprakash Samantaray  
  56. -- Opearion : To delete emplyee details  
  57. -- =============================================  
  58.   
  59. Create Procedure [dbo].[USP_Emp_Delete]    
  60.     @Id int    
  61.     AS    
  62.     Begin    
  63.     Delete From Mas_Employee    
  64.     where Id=@Id    
  65.     End   
  66. GO  
  67.   
  68. ----------------------------------------------------------------------------------------------------------------  
  69.   
  70. IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'Get_AllEmployees')  
  71.     DROP PROCEDURE Get_AllEmployees  
  72. GO  
  73.   
  74. -- =============================================  
  75. -- Author:Satyaprakash Samantaray  
  76. -- Opearion : To get the emplyees details  
  77. -- =============================================  
  78.   
  79. Create Procedure [dbo].[Get_AllEmployees]    
  80.     @Id int = null    
  81.     AS    
  82.     Begin    
  83.     Select E.Id, E.Name, E.Salary,E.DeptID,D.DeptName    
  84.     From Mas_Employee E    
  85.     Join Mas_Department D    
  86.     On E.DeptId = D.DeptId    
  87.     where D.Status = 1    
  88.     And Id = Isnull(@Id, Id)    
  89.     End    
  90. GO  
  91.   
  92. ---------------------------------------------------------------------------------------------------------------- 
Step4

Create a WCF Service Application named "WCF_Crud".



Two files, IService1.cs and Service1.svc, will be added under the project in Solution Explorer.

  
Step5

Then, in WEB.CONFIG file, add connection string and check some system generated codes.

Code Ref
  1. <connectionStrings>  
  2.     <add name="conStr" connectionString="Put Connection string here...." providerName="System.Data.SqlClient"/>  
  3.  </connectionStrings> 
 
 
 
Step6

In Iservices1.cs file, remove all the default code and declare the Service Contracts, Operation Contracts, and Data Contracts.

Code Ref
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8. using System.Data;  
  9. namespace WCF_Crud  
  10. {  
  11.     [ServiceContract]  
  12.     public interface IService1  
  13.     {  
  14.         [OperationContract]  
  15.         string InsertEmpDetails(EmpDetails eDatils);  
  16.         [OperationContract]  
  17.         DataSet GetEmpDetails(EmpDetails eDatils);  
  18.         [OperationContract]  
  19.         DataSet FetchUpdatedRecords(EmpDetails eDatils);  
  20.         [OperationContract]  
  21.         string UpdateEmpDetails(EmpDetails eDatils);  
  22.         [OperationContract]  
  23.         bool DeleteEmpDetails(EmpDetails eDatils);  
  24.     }  
  25.       
  26.     [DataContract]  
  27.     public class EmpDetails  
  28.     {  
  29.         int? eId;  
  30.         string eName = string.Empty;  
  31.         string eSalary = string.Empty;  
  32.         string eDeptId = string.Empty;  
  33.         string eDeptName = string.Empty;  
  34.         [DataMember]  
  35.         public int? Id  
  36.         {  
  37.             get  
  38.             {  
  39.                 return eId;  
  40.             }  
  41.             set  
  42.             {  
  43.                 eId = value;  
  44.             }  
  45.         }  
  46.         [DataMember]  
  47.         public string Name  
  48.         {  
  49.             get  
  50.             {  
  51.                 return eName;  
  52.             }  
  53.             set  
  54.             {  
  55.                 eName = value;  
  56.             }  
  57.         }  
  58.         [DataMember]  
  59.         public string Salary  
  60.         {  
  61.             get  
  62.             {  
  63.                 return eSalary;  
  64.             }  
  65.             set  
  66.             {  
  67.                 eSalary = value;  
  68.             }  
  69.         }  
  70.         [DataMember]  
  71.         public string DeptId  
  72.         {  
  73.             get  
  74.             {  
  75.                 return eDeptId;  
  76.             }  
  77.             set  
  78.             {  
  79.                 eDeptId = value;  
  80.             }  
  81.         }  
  82.         [DataMember]  
  83.         public string DeptName  
  84.         {  
  85.             get  
  86.             {  
  87.                 return eDeptName;  
  88.             }  
  89.             set  
  90.             {  
  91.                 eDeptName = value;  
  92.             }  
  93.         }  
  94.     }  

Code Description

Under [ServiceContract] attribute, I have defined some functions to perform operations using [OperationContract] attribute.
  1. [OperationContract]  
  2.         string InsertEmpDetails(EmpDetails eDatils);  
  3.         [OperationContract]  
  4.         DataSet GetEmpDetails(EmpDetails eDatils);  
  5.         [OperationContract]  
  6.         DataSet FetchUpdatedRecords(EmpDetails eDatils);  
  7.         [OperationContract]  
  8.         string UpdateEmpDetails(EmpDetails eDatils);  
  9.         [OperationContract]  
  10.         bool DeleteEmpDetails(EmpDetails eDatils); 
Use a data contract, as illustrated in the sample below, to add composite types to service operations using [DataMember] attribute. 
  1. public class EmpDetails  
  2.     {  
  3.         int? eId;  
  4.         string eName = string.Empty;  
  5.         string eSalary = string.Empty;  
  6.         string eDeptId = string.Empty;  
  7.         string eDeptName = string.Empty;  
  8.         [DataMember]  
  9.         public int? Id  
  10.         {  
  11.             get  
  12.             {  
  13.                 return eId;  
  14.             }  
  15.             set  
  16.             {  
  17.                 eId = value;  
  18.             }  
  19.         }  
  20.         [DataMember]  
  21.         public string Name  
  22.         {  
  23.             get  
  24.             {  
  25.                 return eName;  
  26.             }  
  27.             set  
  28.             {  
  29.                 eName = value;  
  30.             }  
  31.         }  
  32.         [DataMember]  
  33.         public string Salary  
  34.         {  
  35.             get  
  36.             {  
  37.                 return eSalary;  
  38.             }  
  39.             set  
  40.             {  
  41.                 eSalary = value;  
  42.             }  
  43.         }  
  44.         [DataMember]  
  45.         public string DeptId  
  46.         {  
  47.             get  
  48.             {  
  49.                 return eDeptId;  
  50.             }  
  51.             set  
  52.             {  
  53.                 eDeptId = value;  
  54.             }  
  55.         }  
  56.         [DataMember]  
  57.         public string DeptName  
  58.         {  
  59.             get  
  60.             {  
  61.                 return eDeptName;  
  62.             }  
  63.             set  
  64.             {  
  65.                 eDeptName = value;  
  66.             }  
  67.         }  
  68.     }  
  69. }  
Step7

Now, open the Service.svc.cs file and add the below code. Also, define the methods declared in the IService1.cs above.

Code Ref
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8. using System.Data;  
  9. using System.Data.SqlClient;  
  10. using System.Configuration;  
  11. namespace WCF_Crud  
  12. {  
  13.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.    
  14.     public class Service1 : IService1  
  15.     {  
  16.         SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);  
  17.         public string InsertEmpDetails(EmpDetails eDetails) //For Insert Purpose  
  18.         {  
  19.             string Status;  
  20.             SqlCommand cmd = new SqlCommand("USP_Emp_Insert", con);  
  21.             cmd.CommandType = CommandType.StoredProcedure;  
  22.             cmd.Parameters.AddWithValue("@Name", eDetails.Name);  
  23.             cmd.Parameters.AddWithValue("@Salary", eDetails.Salary);  
  24.             cmd.Parameters.AddWithValue("@DeptId", eDetails.DeptId);  
  25.             if (con.State == ConnectionState.Closed)  
  26.             {  
  27.                 con.Open();  
  28.             }  
  29.             int result = cmd.ExecuteNonQuery();  
  30.             if (result == 1)  
  31.             {  
  32.                 Status = eDetails.Name + " " + eDetails.Salary + " Is Registered Successfully";  
  33.             }  
  34.             else  
  35.             {  
  36.                 Status = eDetails.Name + " " + eDetails.Salary + " could not be registered";  
  37.             }  
  38.             con.Close();  
  39.             return Status;  
  40.         }  
  41.         public DataSet GetEmpDetails(EmpDetails eDetails) //For Details Purpose  
  42.         {  
  43.             SqlCommand cmd = new SqlCommand("Get_AllEmployees", con);  
  44.             cmd.CommandType = CommandType.StoredProcedure;  
  45.             cmd.Parameters.AddWithValue("@Id", eDetails.Id);  
  46.             if (con.State == ConnectionState.Closed)  
  47.             {  
  48.                 con.Open();  
  49.             }  
  50.             SqlDataAdapter da = new SqlDataAdapter(cmd);  
  51.             DataSet ds = new DataSet();  
  52.             da.Fill(ds);  
  53.             cmd.ExecuteNonQuery();  
  54.             con.Close();  
  55.             return ds;  
  56.         }  
  57.         public DataSet FetchUpdatedRecords(EmpDetails eDetails) //For update details Purpose  
  58.         {  
  59.             SqlCommand cmd = new SqlCommand("Get_AllEmployees", con);  
  60.             cmd.CommandType = CommandType.StoredProcedure;  
  61.             cmd.Parameters.AddWithValue("@Id", eDetails.Id);  
  62.             if (con.State == ConnectionState.Closed)  
  63.             {  
  64.                 con.Open();  
  65.             }  
  66.             SqlDataAdapter da = new SqlDataAdapter(cmd);  
  67.             DataSet ds = new DataSet();  
  68.             da.Fill(ds);  
  69.             cmd.ExecuteNonQuery();  
  70.             con.Close();  
  71.             return ds;  
  72.         }  
  73.         public string UpdateEmpDetails(EmpDetails eDetails) //For Update Purpose  
  74.         {  
  75.             string Status;  
  76.             SqlCommand cmd = new SqlCommand("USP_Emp_Update", con);  
  77.             cmd.CommandType = CommandType.StoredProcedure;  
  78.             cmd.Parameters.AddWithValue("@Id", eDetails.Id);  
  79.             cmd.Parameters.AddWithValue("@Name", eDetails.Name);  
  80.             cmd.Parameters.AddWithValue("@Salary", eDetails.Salary);  
  81.             cmd.Parameters.AddWithValue("@DeptId", eDetails.DeptId);  
  82.             if (con.State == ConnectionState.Closed)  
  83.             {  
  84.                 con.Open();  
  85.             }  
  86.             int result = cmd.ExecuteNonQuery();  
  87.             if (result == 1)  
  88.             {  
  89.                 Status = "Record Is Updated successfully";  
  90.             }  
  91.             else  
  92.             {  
  93.                 Status = "Record could not be updated";  
  94.             }  
  95.             con.Close();  
  96.             return Status;  
  97.         }  
  98.         public bool DeleteEmpDetails(EmpDetails eDetails) //For Delete Purpose  
  99.         {  
  100.             SqlCommand cmd = new SqlCommand("USP_Emp_Delete", con);  
  101.             cmd.CommandType = CommandType.StoredProcedure;  
  102.             cmd.Parameters.AddWithValue("@Id", eDetails.Id);  
  103.             if (con.State == ConnectionState.Closed)  
  104.             {  
  105.                 con.Open();  
  106.             }  
  107.             cmd.ExecuteNonQuery();  
  108.             con.Close();  
  109.             return true;  
  110.         }  
  111.     }  

Code Description

Add the namespace lists.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8. using System.Data;  
  9. using System.Data.SqlClient;  
  10. using System.Configuration; 
Here, Service1 class inherits some properties from IService1.
  1. public class Service1 : IService1 
Then, I have added the name of connection string.
  1. SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);   
In code ref. section, I have commented some code with "//" for better information.
 
Go to the Solution Explorer and then right click on Service1.svc. Click on "View in Browser" as shown in the following diagram.

You will get a service link like this : http://localhost:58209/Service1.svc.

It will be used later when consuming this WCF Service in your application. You have now created your WCF Service successfully. And, the next thing is to call/consume this Service in your ASP.NET application.
  
Step8

Create your ASP.NET application named "ConsumeWcfCrud" and consume the preceding new WCF service.



Next, add a webform to your project and name it as Sample.aspx.



To consume/call the WCF Service and its methods, we need to add the service reference. For that, go to Solution Explorer, right click
on the project, and select "Add Service Reference", as shown in the following image.



A new window will appear.



Paste the copied Service URL, localhost:58209/Service1.svc , as shown in the following image.
 
Next, click on the GO button.
 
Expand the Services and click on Iservice1. It will list all the functions/methods created in Services.
 
Change the namespace ServiceReference1 to WcfCrudRef or you can use your own namespace. Then, click on the OK button.

References have been added to the Solution Explorer, as shown in the following image.
 
 
Step9

Add some code in "Samle.aspx".

Code Ref
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Samle.aspx.cs" Inherits="ConsumeWcfCrud.Samle" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title>Satyaprakash Samantaray</title>    
  8.     <%--added css to asp.net server controls--%>   
  9.     <style>    
  10.         .button {    
  11.             background-color: #4CAF50;    
  12.             border: none;    
  13.             color: white;    
  14.             padding: 15px 32px;    
  15.             text-align: center;    
  16.             text-decoration: none;    
  17.             display: inline-block;    
  18.             font-size: 16px;    
  19.             margin: 4px 2px;    
  20.             cursor: pointer;    
  21.         }    
  22.       .DataGridFixedHeader {    
  23.     color: White;    
  24.     font-size: 13px;    
  25.     font-family: Verdana;     
  26.     background-color:yellow    
  27. }    
  28.         .grid_item {     
  29.     background-color: #E3EAEB;    
  30.     border-width: 1px;    
  31.     font-family: Verdana;    
  32.     border-style: solid;    
  33.     font-size: 12pt;    
  34.     color: black;    
  35.     border: 1px solid black;    
  36. }    
  37.         .grid_alternate {    
  38.     border-width: 1px;    
  39.     font-family: Verdana;    
  40.     border-style: solid;    
  41.     font-size: 12pt;    
  42.     color: black;    
  43.     background-color: White;    
  44. }    
  45.         .button4 {    
  46.             border-radius: 9px;    
  47.         }    
  48.         input[type=text], select {    
  49.         width: 50%;    
  50.         padding: 12px 20px;    
  51.         margin: 10px 0;    
  52.         display: inline-block;    
  53.         border: 1px solid #ccc;    
  54.         border-radius: 4px;    
  55.         box-sizing: border-box;    
  56.         font-family: 'Montserrat', sans-serif;      
  57.         text-indent: 10px;      
  58.         color: blue;      
  59.         text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);      
  60.         font-size: 20px;      
  61.     }    
  62.     </style>    
  63.     <%--added css to asp.net server controls--%>   
  64.   
  65. <%--added script file for asp.net server controls validations--%>   
  66.     <script language="javascript" src="../Scripts/Validation.js" type="text/javascript"></script>    
  67.     <script language="javascript" type="text/javascript">  
  68.         function Validation() {  
  69.             if (Required('<%=txtName.ClientID%>''Name'))  
  70.                 if (Required('<%=txtSalary.ClientID%>''Salary'))  
  71.                     if (Required('<%=txtDeptId.ClientID%>''Dept ID'))  
  72.                         return true;  
  73.             return false;  
  74.         }  
  75.     </script>    
  76. <%--added script file for asp.net server controls validations--%>   
  77. </head>  
  78.   
  79. <body>  
  80.     <form id="form1" runat="server">    
  81.         <fieldset>    
  82.     <legend style="font-family: Arial Black;background-color:yellow; color:red; font-size:larger;font-style: oblique">Satyaprakash's WCF Real-Time Project</legend>   
  83.                 <table  align="center">    
  84.                     <tr>    
  85.                         <td style="text-align:center">    
  86.                             <asp:TextBox ID="txtName" runat="server" placeholder="Enter Name.." ></asp:TextBox>    
  87.                         </td>    
  88.                     </tr>    
  89.                     <tr>    
  90.                         <td style="text-align:center">    
  91.                             <asp:TextBox ID="txtSalary" runat="server" placeholder="Enter Salary.."></asp:TextBox>    
  92.                         </td>    
  93.                     </tr>    
  94.                     <tr>    
  95.                         <td style="text-align:center">    
  96.                             <asp:TextBox ID="txtDeptId" runat="server" placeholder="Enter DeptID.."></asp:TextBox>    
  97.                         </td>    
  98.                     </tr>    
  99.                     <tr>    
  100.                        <td align="center">    
  101.                             <asp:Button ID="btnSubmit" runat="server" class="button button4" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="javascript:return Validation();"/>    
  102.                             <asp:Button ID="btnCancel" runat="server" class="button button4" Text="Cancel" OnClick="btnCancel_Click" />    
  103.                         </td>    
  104.                     </tr>    
  105.                     <tr>    
  106.                         <td align="center">    
  107.                             <asp:Label ID="lblStatus" runat="server"></asp:Label>    
  108.                         </td>    
  109.                     </tr>    
  110.                     <tr>    
  111.                         <td align="center" colspan="2" style="background-color:yellowgreen;width: 100%;">  
  112.                             <span style="font-family: Arial Black;color:red;background-color:yellow;font-size:larger;font-style: oblique">EMPLOYEE SUMMARY</span>  
  113.                             <br />    
  114.                         </td>    
  115.                     </tr>    
  116.                     <tr>   
  117.                         <td colspan="2">    
  118.                             <%--added gridview style layout and functionality  here--%>  
  119.                             <asp:GridView ID="grdWcfTest" runat="server" AllowPaging="true" CellPadding="2" EnableModelValidation="True"    
  120.                                         ForeColor="red" GridLines="Both" ItemStyle-HorizontalAlign="center" EmptyDataText="There Is No Records In Database!" AutoGenerateColumns="false" Width="1100px"    
  121.                                 HeaderStyle-ForeColor="blue">    
  122.                                 <HeaderStyle CssClass="DataGridFixedHeader" />    
  123.                                 <RowStyle CssClass="grid_item" />    
  124.                                 <AlternatingRowStyle CssClass="grid_alternate" />    
  125.                                 <FooterStyle CssClass="DataGridFixedHeader" />   
  126.                                 <Columns>    
  127.                                     <asp:TemplateField HeaderText="Name">    
  128.                                         <HeaderStyle HorizontalAlign="Left" />    
  129.                                         <ItemStyle HorizontalAlign="Left" />   
  130.                                         <ItemTemplate>    
  131.                                             <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name")%>'>    
  132.                                             </asp:Label>    
  133.                                             <asp:Label ID="lblId" runat="server" Visible="false" Text='<%#Eval("Id")%>'>    
  134.                                             </asp:Label>    
  135.                                         </ItemTemplate>    
  136.                                     </asp:TemplateField>    
  137.                                     <asp:TemplateField HeaderText="Salary">    
  138.                                         <HeaderStyle HorizontalAlign="Left" />    
  139.                                         <ItemStyle HorizontalAlign="Left" />   
  140.                                         <ItemTemplate>                                         
  141.                                             <asp:Label ID="lblSalary" runat="server" Text='<%#Eval("Salary") %>'>    
  142.                                             </asp:Label>    
  143.                                         </ItemTemplate>    
  144.                                     </asp:TemplateField>    
  145.                                     <asp:TemplateField HeaderText="DeptId">   
  146.                                         <HeaderStyle HorizontalAlign="Left" />    
  147.                                         <ItemStyle HorizontalAlign="Left" />    
  148.                                         <ItemTemplate>                                              
  149.                                             <asp:Label ID="lblDeptId" runat="server" Text='<%#Eval("DeptId") %>'>    
  150.                                             </asp:Label>    
  151.                                         </ItemTemplate>    
  152.                                     </asp:TemplateField>    
  153.                                     <asp:TemplateField HeaderText="Edit">   
  154.                                         <HeaderStyle HorizontalAlign="Left" />    
  155.                                         <ItemStyle HorizontalAlign="Left" />    
  156.                                         <ItemTemplate>    
  157.                                             <asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CausesValidation="false"    
  158.         
  159.     CommandArgument='    
  160.                                                 <%#Eval("Id") %>' OnCommand="lnkEdit_Command" ToolTip="Edit" />    
  161.                                             </ItemTemplate>    
  162.                                         </asp:TemplateField>    
  163.                                         <asp:TemplateField HeaderText="Delete">    
  164.                                         <HeaderStyle HorizontalAlign="Left" />    
  165.                                         <ItemStyle HorizontalAlign="Left" />   
  166.                                             <ItemTemplate>    
  167.                                                 <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CausesValidation="false"    
  168.         
  169.     CommandArgument='    
  170.                                                     <%#Eval("Id") %>' CommandName="Delete" OnCommand="lnkDelete_Command"    
  171.         
  172.     OnClientClick="return confirm('Are you sure you want to delete?')" ToolTip="Delete" />    
  173.                                                 </ItemTemplate>    
  174.                                             </asp:TemplateField>    
  175.                                         </Columns>    
  176.                                     </asp:GridView>    
  177.                             <%--added gridview style layout and functionality  here--%>  
  178.                                 </td>    
  179.                             </tr>    
  180.                     </table>    
  181.             </fieldset>   
  182.     </form>    
  183. </body>  
  184.     <br />    
  185.     <br />    
  186.   
  187.     <%--added footer related information here--%>  
  188. <footer>      
  189.         <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© <script> document.write(new Date().toDateString()); </script></p>      
  190.  </footer>   
  191.     <%--added footer related information here--%>  
  192.   
  193. </html> 
Code Description

I have added some description with commented lines using "<%-- --%>"  to describe the above code.
 
Step10

Add the following code in "Samle.aspx.cs".

Code Ref
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. using System.Configuration;  
  10. using ConsumeWcfCrud.WcfCrudRef;  
  11.   
  12. namespace ConsumeWcfCrud  
  13. {  
  14.     public partial class Samle : System.Web.UI.Page  
  15.     {  
  16.         #region Variable Declaration  
  17.         WcfCrudRef.Service1Client obj = new WcfCrudRef.Service1Client(); //WCF SERVICE REFERENCE ADDED HERE.  
  18.         #endregion  
  19.         #region User Define Methods  
  20.         private void ClearControls() //Defined a function to reset asp.net server controls.  
  21.         {  
  22.             txtName.Text = string.Empty;  
  23.             txtSalary.Text = string.Empty;  
  24.             txtDeptId.Text = string.Empty;  
  25.             btnSubmit.Text = "Submit";  
  26.             txtName.Focus();  
  27.         }  
  28.         private void BindEmpDetails(int? Id) //This function defined for bind to grid view.  
  29.         {  
  30.             EmpDetails eDetails = new EmpDetails();  
  31.             DataSet ds = new DataSet();  
  32.             ds = obj.GetEmpDetails(eDetails);  
  33.             grdWcfTest.DataSource = ds;  
  34.             grdWcfTest.DataBind();  
  35.         }  
  36.         private void SaveEmpDetails() //This function defined for save data.  
  37.         {  
  38.             EmpDetails eDetails = new EmpDetails();  
  39.             eDetails.Name = txtName.Text.Trim();  
  40.             eDetails.Salary = txtSalary.Text.Trim();  
  41.             eDetails.DeptId = txtDeptId.Text.Trim();  
  42.             lblStatus.Text = obj.InsertEmpDetails(eDetails);  
  43.             lblStatus.ForeColor = System.Drawing.Color.Blue;  
  44.             ClearControls();  
  45.             BindEmpDetails(null);  
  46.         }  
  47.         private void UpdateEmpDetails() //This function defined for update data.  
  48.         {  
  49.             EmpDetails eDetails = new EmpDetails();  
  50.             eDetails.Id = Convert.ToInt32(ViewState["Id"].ToString());  
  51.             eDetails.Name = txtName.Text.Trim();  
  52.             eDetails.Salary = txtSalary.Text.Trim();  
  53.             eDetails.DeptId = txtDeptId.Text.Trim();  
  54.             obj.UpdateEmpDetails(eDetails);  
  55.             lblStatus.Text = obj.UpdateEmpDetails(eDetails);  
  56.             lblStatus.ForeColor = System.Drawing.Color.Maroon;  
  57.             ClearControls();  
  58.             BindEmpDetails(null);  
  59.         }  
  60.         #endregion  
  61.         #region Page Event HandlersBindEmpDetailsBindEmpDetails  
  62.         protected void Page_Load(object sender, EventArgs e) //In page load event the function " BindEmpDetails()" for bind to gridview.  
  63.         {  
  64.             if (!Page.IsPostBack)  
  65.             {  
  66.                 BindEmpDetails(null);  
  67.                 ClearControls();  
  68.                 lblStatus.Text = String.Empty;  
  69.             }  
  70.         }  
  71.         protected void btnSubmit_Click(object sender, EventArgs e) //In submit button click event i added "SaveEmpDetails()" to insert new records  
  72.         {  
  73.             if (btnSubmit.Text == "Update")  
  74.             {  
  75.                 UpdateEmpDetails(); //for update existing records.  
  76.             }  
  77.             else  
  78.             {  
  79.                 SaveEmpDetails(); //for insert new records  
  80.             }  
  81.         }  
  82.         protected void lnkEdit_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)  
  83.         {  
  84.             EmpDetails eDetails = new EmpDetails(); //By clicking edit link button in gridview all existing data will come to respected controls.  
  85.             eDetails.Id = int.Parse(e.CommandArgument.ToString());  
  86.             ViewState["Id"] = eDetails.Id; //Viewstate variable helps to pass id of respected data.  
  87.             DataSet ds = new DataSet();  
  88.             ds = obj.FetchUpdatedRecords(eDetails); //this function will help you fetch updated records.  
  89.             if (ds.Tables[0].Rows.Count > 0)  
  90.             {  
  91.                 txtName.Text = ds.Tables[0].Rows[0]["Name"].ToString();  
  92.                 txtSalary.Text = ds.Tables[0].Rows[0]["Salary"].ToString();  
  93.                 txtDeptId.Text = ds.Tables[0].Rows[0]["DeptId"].ToString();  
  94.                 btnSubmit.Text = "Update"//The button text will be changed to "Update".  
  95.             }  
  96.         }  
  97.         protected void lnkDelete_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)  
  98.         {  
  99.             EmpDetails eDetails = new EmpDetails(); //This part helps us to delete records using Delete link button.  
  100.             eDetails.Id = int.Parse(e.CommandArgument.ToString());  
  101.             if (obj.DeleteEmpDetails(eDetails) == true//Here the function defined.  
  102.             {  
  103.                 lblStatus.Text = "Record Is Deleted Successfully";  
  104.                 lblStatus.ForeColor = System.Drawing.Color.Red;  
  105.             }  
  106.             else  
  107.             {  
  108.                 lblStatus.Text = "Record couldn't be deleted";  
  109.                 lblStatus.ForeColor = System.Drawing.Color.OrangeRed;  
  110.             }  
  111.             BindEmpDetails(null); //As soon as any change in records the fast action will be happened in gridview using this function.  
  112.         }  
  113.         protected void btnCancel_Click(object sender, EventArgs e)  
  114.         {  
  115.             ClearControls(); //This function helps to reset control's values.  
  116.             lblStatus.Text = string.Empty;  
  117.         }  
  118.         #endregion  
  119.     }  

Code Description

Some important namespaces are added here.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. using System.Configuration;  
  10. using ConsumeWcfCrud.WcfCrudRef;  
The label text color will be changed for each operation. For example, for deleting records, I have assigned the red color to be shown to the end user.  lblStatus.ForeColor = System.Drawing.Color.Red; 
 
OUTPUT
 
No records.



For Insert.



For Update.

 


For Delete.


 


For Text Validation.




For Chrome View.



That's it. I hope you understood the process very well. For any query or suggestions, please comment below.