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.
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
Create two tables, as mentioned below.
Scripts
- CREATE TABLE [dbo].[Mas_Employee](
- [Id] [int] IDENTITY(1,1) NOT NULL,
- [Name] [varchar](50) NOT NULL,
- [Salary] [varchar](50) NOT NULL,
- [DeptId] [int] NOT NULL,
- [Status] [int] NULL,
- CONSTRAINT [PK_Mas_Employee] PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
- CREATE TABLE [dbo].[Mas_Department](
- [DeptId] [int] IDENTITY(1,1) NOT NULL,
- [DeptName] [varchar](50) NOT NULL,
- [Status] [int] NULL,
- CONSTRAINT [PK_Mas_Department] PRIMARY KEY CLUSTERED
- (
- [DeptId] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
Enter dummy data in Mas_Department table. That will be needed during inner join, with first table to fetch records.
- SET IDENTITY_INSERT [dbo].[Mas_Department] ON
- GO
- INSERT [dbo].[Mas_Department] ([DeptId], [DeptName], [Status]) VALUES (1, N'IT', 1)
- GO
- INSERT [dbo].[Mas_Department] ([DeptId], [DeptName], [Status]) VALUES (2, N'HR', 1)
- GO
- INSERT [dbo].[Mas_Department] ([DeptId], [DeptName], [Status]) VALUES (3, N'ACCOUNTS', 1)
- GO
- SET IDENTITY_INSERT [dbo].[Mas_Department] OFF
- GO
Create list of procedures to perform operations.
- IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'USP_Emp_Insert')
- DROP PROCEDURE USP_Emp_Insert
- GO
- -- =============================================
- -- Author:Satyaprakash Samantaray
- -- Opearion : To Insert emplyee details
- -- =============================================
- Create Procedure [dbo].[USP_Emp_Insert]
- @Name varchar(50),
- @Salary int,
- @DeptId int
- AS
- Begin
- Insert into Mas_Employee
- (Name,Salary,DeptId) Values
- (@Name,@Salary,@DeptId)
- End
- GO
- ----------------------------------------------------------------------------------------------------------------
- IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'USP_Emp_Update')
- DROP PROCEDURE USP_Emp_Update
- GO
- -- =============================================
- -- Author:Satyaprakash Samantaray
- -- Opearion : To update the emplyee details
- -- =============================================
- Create Procedure [dbo].[USP_Emp_Update]
- @Id int,
- @Name varchar(50),
- @Salary int,
- @DeptId int
- AS
- Begin
- update Mas_Employee Set
- Name=@Name,
- Salary=@Salary,
- DeptId=@DeptId
- where Id=@Id
- End
- GO
- ----------------------------------------------------------------------------------------------------------------
- IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'USP_Emp_Delete')
- DROP PROCEDURE USP_Emp_Delete
- GO
- -- =============================================
- -- Author:Satyaprakash Samantaray
- -- Opearion : To delete emplyee details
- -- =============================================
- Create Procedure [dbo].[USP_Emp_Delete]
- @Id int
- AS
- Begin
- Delete From Mas_Employee
- where Id=@Id
- End
- GO
- ----------------------------------------------------------------------------------------------------------------
- IF EXISTS(SELECT NAME FROM sys.objects WHERE type = 'P' AND name = 'Get_AllEmployees')
- DROP PROCEDURE Get_AllEmployees
- GO
- -- =============================================
- -- Author:Satyaprakash Samantaray
- -- Opearion : To get the emplyees details
- -- =============================================
- Create Procedure [dbo].[Get_AllEmployees]
- @Id int = null
- AS
- Begin
- Select E.Id, E.Name, E.Salary,E.DeptID,D.DeptName
- From Mas_Employee E
- Join Mas_Department D
- On E.DeptId = D.DeptId
- where D.Status = 1
- And Id = Isnull(@Id, Id)
- End
- GO
- ----------------------------------------------------------------------------------------------------------------
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.

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
Then, in WEB.CONFIG file, add connection string and check some system generated codes.
Code Ref
- <connectionStrings>
- <add name="conStr" connectionString="Put Connection string here...." providerName="System.Data.SqlClient"/>
- </connectionStrings>

Step6
In Iservices1.cs file, remove all the default code and declare the Service Contracts, Operation Contracts, and Data Contracts.
Code Ref
In Iservices1.cs file, remove all the default code and declare the Service Contracts, Operation Contracts, and Data Contracts.
Code Ref
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.ServiceModel.Web;
- using System.Text;
- using System.Data;
- namespace WCF_Crud
- {
- [ServiceContract]
- public interface IService1
- {
- [OperationContract]
- string InsertEmpDetails(EmpDetails eDatils);
- [OperationContract]
- DataSet GetEmpDetails(EmpDetails eDatils);
- [OperationContract]
- DataSet FetchUpdatedRecords(EmpDetails eDatils);
- [OperationContract]
- string UpdateEmpDetails(EmpDetails eDatils);
- [OperationContract]
- bool DeleteEmpDetails(EmpDetails eDatils);
- }
- [DataContract]
- public class EmpDetails
- {
- int? eId;
- string eName = string.Empty;
- string eSalary = string.Empty;
- string eDeptId = string.Empty;
- string eDeptName = string.Empty;
- [DataMember]
- public int? Id
- {
- get
- {
- return eId;
- }
- set
- {
- eId = value;
- }
- }
- [DataMember]
- public string Name
- {
- get
- {
- return eName;
- }
- set
- {
- eName = value;
- }
- }
- [DataMember]
- public string Salary
- {
- get
- {
- return eSalary;
- }
- set
- {
- eSalary = value;
- }
- }
- [DataMember]
- public string DeptId
- {
- get
- {
- return eDeptId;
- }
- set
- {
- eDeptId = value;
- }
- }
- [DataMember]
- public string DeptName
- {
- get
- {
- return eDeptName;
- }
- set
- {
- eDeptName = value;
- }
- }
- }
- }
Under [ServiceContract] attribute, I have defined some functions to perform operations using [OperationContract] attribute.
- [OperationContract]
- string InsertEmpDetails(EmpDetails eDatils);
- [OperationContract]
- DataSet GetEmpDetails(EmpDetails eDatils);
- [OperationContract]
- DataSet FetchUpdatedRecords(EmpDetails eDatils);
- [OperationContract]
- string UpdateEmpDetails(EmpDetails eDatils);
- [OperationContract]
- bool DeleteEmpDetails(EmpDetails eDatils);
- public class EmpDetails
- {
- int? eId;
- string eName = string.Empty;
- string eSalary = string.Empty;
- string eDeptId = string.Empty;
- string eDeptName = string.Empty;
- [DataMember]
- public int? Id
- {
- get
- {
- return eId;
- }
- set
- {
- eId = value;
- }
- }
- [DataMember]
- public string Name
- {
- get
- {
- return eName;
- }
- set
- {
- eName = value;
- }
- }
- [DataMember]
- public string Salary
- {
- get
- {
- return eSalary;
- }
- set
- {
- eSalary = value;
- }
- }
- [DataMember]
- public string DeptId
- {
- get
- {
- return eDeptId;
- }
- set
- {
- eDeptId = value;
- }
- }
- [DataMember]
- public string DeptName
- {
- get
- {
- return eDeptName;
- }
- set
- {
- eDeptName = value;
- }
- }
- }
- }
Now, open the Service.svc.cs file and add the below code. Also, define the methods declared in the IService1.cs above.
Code Ref
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.ServiceModel.Web;
- using System.Text;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- namespace WCF_Crud
- {
- // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
- public class Service1 : IService1
- {
- SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
- public string InsertEmpDetails(EmpDetails eDetails) //For Insert Purpose
- {
- string Status;
- SqlCommand cmd = new SqlCommand("USP_Emp_Insert", con);
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Name", eDetails.Name);
- cmd.Parameters.AddWithValue("@Salary", eDetails.Salary);
- cmd.Parameters.AddWithValue("@DeptId", eDetails.DeptId);
- if (con.State == ConnectionState.Closed)
- {
- con.Open();
- }
- int result = cmd.ExecuteNonQuery();
- if (result == 1)
- {
- Status = eDetails.Name + " " + eDetails.Salary + " Is Registered Successfully";
- }
- else
- {
- Status = eDetails.Name + " " + eDetails.Salary + " could not be registered";
- }
- con.Close();
- return Status;
- }
- public DataSet GetEmpDetails(EmpDetails eDetails) //For Details Purpose
- {
- SqlCommand cmd = new SqlCommand("Get_AllEmployees", con);
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Id", eDetails.Id);
- if (con.State == ConnectionState.Closed)
- {
- con.Open();
- }
- SqlDataAdapter da = new SqlDataAdapter(cmd);
- DataSet ds = new DataSet();
- da.Fill(ds);
- cmd.ExecuteNonQuery();
- con.Close();
- return ds;
- }
- public DataSet FetchUpdatedRecords(EmpDetails eDetails) //For update details Purpose
- {
- SqlCommand cmd = new SqlCommand("Get_AllEmployees", con);
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Id", eDetails.Id);
- if (con.State == ConnectionState.Closed)
- {
- con.Open();
- }
- SqlDataAdapter da = new SqlDataAdapter(cmd);
- DataSet ds = new DataSet();
- da.Fill(ds);
- cmd.ExecuteNonQuery();
- con.Close();
- return ds;
- }
- public string UpdateEmpDetails(EmpDetails eDetails) //For Update Purpose
- {
- string Status;
- SqlCommand cmd = new SqlCommand("USP_Emp_Update", con);
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Id", eDetails.Id);
- cmd.Parameters.AddWithValue("@Name", eDetails.Name);
- cmd.Parameters.AddWithValue("@Salary", eDetails.Salary);
- cmd.Parameters.AddWithValue("@DeptId", eDetails.DeptId);
- if (con.State == ConnectionState.Closed)
- {
- con.Open();
- }
- int result = cmd.ExecuteNonQuery();
- if (result == 1)
- {
- Status = "Record Is Updated successfully";
- }
- else
- {
- Status = "Record could not be updated";
- }
- con.Close();
- return Status;
- }
- public bool DeleteEmpDetails(EmpDetails eDetails) //For Delete Purpose
- {
- SqlCommand cmd = new SqlCommand("USP_Emp_Delete", con);
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Id", eDetails.Id);
- if (con.State == ConnectionState.Closed)
- {
- con.Open();
- }
- cmd.ExecuteNonQuery();
- con.Close();
- return true;
- }
- }
- }
Add the namespace lists.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.ServiceModel.Web;
- using System.Text;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- public class Service1 : IService1
Then, I have added the name of connection string.
- SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
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.
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.
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.
References have been added to the Solution Explorer, as shown in the following image.

Step9
Add some code in "Samle.aspx".
Code Ref
Add some code in "Samle.aspx".
Code Ref
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Samle.aspx.cs" Inherits="ConsumeWcfCrud.Samle" %>
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>Satyaprakash Samantaray</title>
- <%--added css to asp.net server controls--%>
- <style>
- .button {
- background-color: #4CAF50;
- border: none;
- color: white;
- padding: 15px 32px;
- text-align: center;
- text-decoration: none;
- display: inline-block;
- font-size: 16px;
- margin: 4px 2px;
- cursor: pointer;
- }
- .DataGridFixedHeader {
- color: White;
- font-size: 13px;
- font-family: Verdana;
- background-color:yellow
- }
- .grid_item {
- background-color: #E3EAEB;
- border-width: 1px;
- font-family: Verdana;
- border-style: solid;
- font-size: 12pt;
- color: black;
- border: 1px solid black;
- }
- .grid_alternate {
- border-width: 1px;
- font-family: Verdana;
- border-style: solid;
- font-size: 12pt;
- color: black;
- background-color: White;
- }
- .button4 {
- border-radius: 9px;
- }
- input[type=text], select {
- width: 50%;
- padding: 12px 20px;
- margin: 10px 0;
- display: inline-block;
- border: 1px solid #ccc;
- border-radius: 4px;
- box-sizing: border-box;
- font-family: 'Montserrat', sans-serif;
- text-indent: 10px;
- color: blue;
- text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
- font-size: 20px;
- }
- </style>
- <%--added css to asp.net server controls--%>
- <%--added script file for asp.net server controls validations--%>
- <script language="javascript" src="../Scripts/Validation.js" type="text/javascript"></script>
- <script language="javascript" type="text/javascript">
- function Validation() {
- if (Required('<%=txtName.ClientID%>', 'Name'))
- if (Required('<%=txtSalary.ClientID%>', 'Salary'))
- if (Required('<%=txtDeptId.ClientID%>', 'Dept ID'))
- return true;
- return false;
- }
- </script>
- <%--added script file for asp.net server controls validations--%>
- </head>
- <body>
- <form id="form1" runat="server">
- <fieldset>
- <legend style="font-family: Arial Black;background-color:yellow; color:red; font-size:larger;font-style: oblique">Satyaprakash's WCF Real-Time Project</legend>
- <table align="center">
- <tr>
- <td style="text-align:center">
- <asp:TextBox ID="txtName" runat="server" placeholder="Enter Name.." ></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td style="text-align:center">
- <asp:TextBox ID="txtSalary" runat="server" placeholder="Enter Salary.."></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td style="text-align:center">
- <asp:TextBox ID="txtDeptId" runat="server" placeholder="Enter DeptID.."></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td align="center">
- <asp:Button ID="btnSubmit" runat="server" class="button button4" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="javascript:return Validation();"/>
- <asp:Button ID="btnCancel" runat="server" class="button button4" Text="Cancel" OnClick="btnCancel_Click" />
- </td>
- </tr>
- <tr>
- <td align="center">
- <asp:Label ID="lblStatus" runat="server"></asp:Label>
- </td>
- </tr>
- <tr>
- <td align="center" colspan="2" style="background-color:yellowgreen;width: 100%;">
- <span style="font-family: Arial Black;color:red;background-color:yellow;font-size:larger;font-style: oblique">EMPLOYEE SUMMARY</span>
- <br />
- </td>
- </tr>
- <tr>
- <td colspan="2">
- <%--added gridview style layout and functionality here--%>
- <asp:GridView ID="grdWcfTest" runat="server" AllowPaging="true" CellPadding="2" EnableModelValidation="True"
- ForeColor="red" GridLines="Both" ItemStyle-HorizontalAlign="center" EmptyDataText="There Is No Records In Database!" AutoGenerateColumns="false" Width="1100px"
- HeaderStyle-ForeColor="blue">
- <HeaderStyle CssClass="DataGridFixedHeader" />
- <RowStyle CssClass="grid_item" />
- <AlternatingRowStyle CssClass="grid_alternate" />
- <FooterStyle CssClass="DataGridFixedHeader" />
- <Columns>
- <asp:TemplateField HeaderText="Name">
- <HeaderStyle HorizontalAlign="Left" />
- <ItemStyle HorizontalAlign="Left" />
- <ItemTemplate>
- <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name")%>'>
- </asp:Label>
- <asp:Label ID="lblId" runat="server" Visible="false" Text='<%#Eval("Id")%>'>
- </asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Salary">
- <HeaderStyle HorizontalAlign="Left" />
- <ItemStyle HorizontalAlign="Left" />
- <ItemTemplate>
- <asp:Label ID="lblSalary" runat="server" Text='<%#Eval("Salary") %>'>
- </asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="DeptId">
- <HeaderStyle HorizontalAlign="Left" />
- <ItemStyle HorizontalAlign="Left" />
- <ItemTemplate>
- <asp:Label ID="lblDeptId" runat="server" Text='<%#Eval("DeptId") %>'>
- </asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Edit">
- <HeaderStyle HorizontalAlign="Left" />
- <ItemStyle HorizontalAlign="Left" />
- <ItemTemplate>
- <asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CausesValidation="false"
- CommandArgument='
- <%#Eval("Id") %>' OnCommand="lnkEdit_Command" ToolTip="Edit" />
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Delete">
- <HeaderStyle HorizontalAlign="Left" />
- <ItemStyle HorizontalAlign="Left" />
- <ItemTemplate>
- <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CausesValidation="false"
- CommandArgument='
- <%#Eval("Id") %>' CommandName="Delete" OnCommand="lnkDelete_Command"
- OnClientClick="return confirm('Are you sure you want to delete?')" ToolTip="Delete" />
- </ItemTemplate>
- </asp:TemplateField>
- </Columns>
- </asp:GridView>
- <%--added gridview style layout and functionality here--%>
- </td>
- </tr>
- </table>
- </fieldset>
- </form>
- </body>
- <br />
- <br />
- <%--added footer related information here--%>
- <footer>
- <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© <script> document.write(new Date().toDateString()); </script></p>
- </footer>
- <%--added footer related information here--%>
- </html>
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
Add the following code in "Samle.aspx.cs".
Code Ref
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- using ConsumeWcfCrud.WcfCrudRef;
- namespace ConsumeWcfCrud
- {
- public partial class Samle : System.Web.UI.Page
- {
- #region Variable Declaration
- WcfCrudRef.Service1Client obj = new WcfCrudRef.Service1Client(); //WCF SERVICE REFERENCE ADDED HERE.
- #endregion
- #region User Define Methods
- private void ClearControls() //Defined a function to reset asp.net server controls.
- {
- txtName.Text = string.Empty;
- txtSalary.Text = string.Empty;
- txtDeptId.Text = string.Empty;
- btnSubmit.Text = "Submit";
- txtName.Focus();
- }
- private void BindEmpDetails(int? Id) //This function defined for bind to grid view.
- {
- EmpDetails eDetails = new EmpDetails();
- DataSet ds = new DataSet();
- ds = obj.GetEmpDetails(eDetails);
- grdWcfTest.DataSource = ds;
- grdWcfTest.DataBind();
- }
- private void SaveEmpDetails() //This function defined for save data.
- {
- EmpDetails eDetails = new EmpDetails();
- eDetails.Name = txtName.Text.Trim();
- eDetails.Salary = txtSalary.Text.Trim();
- eDetails.DeptId = txtDeptId.Text.Trim();
- lblStatus.Text = obj.InsertEmpDetails(eDetails);
- lblStatus.ForeColor = System.Drawing.Color.Blue;
- ClearControls();
- BindEmpDetails(null);
- }
- private void UpdateEmpDetails() //This function defined for update data.
- {
- EmpDetails eDetails = new EmpDetails();
- eDetails.Id = Convert.ToInt32(ViewState["Id"].ToString());
- eDetails.Name = txtName.Text.Trim();
- eDetails.Salary = txtSalary.Text.Trim();
- eDetails.DeptId = txtDeptId.Text.Trim();
- obj.UpdateEmpDetails(eDetails);
- lblStatus.Text = obj.UpdateEmpDetails(eDetails);
- lblStatus.ForeColor = System.Drawing.Color.Maroon;
- ClearControls();
- BindEmpDetails(null);
- }
- #endregion
- #region Page Event HandlersBindEmpDetailsBindEmpDetails
- protected void Page_Load(object sender, EventArgs e) //In page load event the function " BindEmpDetails()" for bind to gridview.
- {
- if (!Page.IsPostBack)
- {
- BindEmpDetails(null);
- ClearControls();
- lblStatus.Text = String.Empty;
- }
- }
- protected void btnSubmit_Click(object sender, EventArgs e) //In submit button click event i added "SaveEmpDetails()" to insert new records
- {
- if (btnSubmit.Text == "Update")
- {
- UpdateEmpDetails(); //for update existing records.
- }
- else
- {
- SaveEmpDetails(); //for insert new records
- }
- }
- protected void lnkEdit_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
- {
- EmpDetails eDetails = new EmpDetails(); //By clicking edit link button in gridview all existing data will come to respected controls.
- eDetails.Id = int.Parse(e.CommandArgument.ToString());
- ViewState["Id"] = eDetails.Id; //Viewstate variable helps to pass id of respected data.
- DataSet ds = new DataSet();
- ds = obj.FetchUpdatedRecords(eDetails); //this function will help you fetch updated records.
- if (ds.Tables[0].Rows.Count > 0)
- {
- txtName.Text = ds.Tables[0].Rows[0]["Name"].ToString();
- txtSalary.Text = ds.Tables[0].Rows[0]["Salary"].ToString();
- txtDeptId.Text = ds.Tables[0].Rows[0]["DeptId"].ToString();
- btnSubmit.Text = "Update"; //The button text will be changed to "Update".
- }
- }
- protected void lnkDelete_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
- {
- EmpDetails eDetails = new EmpDetails(); //This part helps us to delete records using Delete link button.
- eDetails.Id = int.Parse(e.CommandArgument.ToString());
- if (obj.DeleteEmpDetails(eDetails) == true) //Here the function defined.
- {
- lblStatus.Text = "Record Is Deleted Successfully";
- lblStatus.ForeColor = System.Drawing.Color.Red;
- }
- else
- {
- lblStatus.Text = "Record couldn't be deleted";
- lblStatus.ForeColor = System.Drawing.Color.OrangeRed;
- }
- BindEmpDetails(null); //As soon as any change in records the fast action will be happened in gridview using this function.
- }
- protected void btnCancel_Click(object sender, EventArgs e)
- {
- ClearControls(); //This function helps to reset control's values.
- lblStatus.Text = string.Empty;
- }
- #endregion
- }
- }
Some important namespaces are added here.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- using ConsumeWcfCrud.WcfCrudRef;
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.

Join the conversation! Your thoughts help the community grow.