In this article I will explain how to perform Select, Insert, Edit, Update and Delete operations using a WCF Service and OperationContract methods in ASP.Net.
In order to illustrate, I’ll be using a GridView in which I will perform Insert, Edit, Update and Delete operations using a WCF Service in ASP.Net, C# and VB.Net.
 
 
Database
I have made use of the following table Customers with the schema as follows.
Select Insert Edit Update Delete using WCF Service in ASP.Net
 
I have already inserted few records in the table.
Select Insert Edit Update Delete using WCF Service in ASP.Net
 
Note: You can download the database table SQL by clicking the download link below.
         Download SQL file
 
 
Adding WCF Service to Project
The very first thing you need to do is add a WCF service to your project by clicking on Add New Items as shown below.
Select Insert Edit Update Delete using WCF Service in ASP.Net
 
 
Building the WCF Service
The next task is to add the OperationContract methods to the WCF Service that will perform the task of Select, Insert, Update and Delete in the database.
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.ServiceModel;
using System.Runtime.Serialization;
 
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.ServiceModel
Imports System.Runtime.Serialization
 
IService Interface
The IService Interface class has a DataContract class named CustomerData which contains a DataTable Property CustomersTable which will be used to send the data from the WCF Service to the Web Application.
The IService Interface has four methods decorated with OperationContract attribute to perform Select, Insert, Update and Delete operations.
C#
[ServiceContract]
public interface IService
{
    [OperationContract]
    CustomerData Get();
 
    [OperationContract]
    void Insert(string name, string country);
 
    [OperationContract]
    void Update(int customerId, string name, string country);
 
    [OperationContract]
    void Delete(int customerId);
}
 
[DataContract]
public class CustomerData
{
    public CustomerData()
    {
        this.CustomersTable = new DataTable("CustomersData");
    }
 
    [DataMember]
    public DataTable CustomersTable { get; set; }
}
 
VB.Net
<ServiceContract()> _
Public Interface IService
    <OperationContract()> _
    Function [Get]() As CustomerData
 
    <OperationContract()> _
    Sub Insert(name As String, country As String)
 
    <OperationContract()> _
    Sub Update(customerId As Integer, name As String, country As String)
 
    <OperationContract()> _
    Sub Delete(customerId As Integer)
End Interface
 
<DataContract()> _
Public Class CustomerData
    Public Sub New()
        Me.CustomersTable = New DataTable("CustomersData")
    End Sub
 
    <DataMember()> _
    Public Property CustomersTable() As DataTable
End Class
 
Service Class
The IService Interface has been implemented in a class named Service which contains the definition of the four methods declared in the IService Interface.
The Get method gets the records from the Customers table and populates the DataTable of the CustomerData class object which finally is returned to the client accessing the WCF service.
The Insert, Update and Delete methods perform the Insert, Update and Delete operations respectively.
C#
public class Service : IService
{
    public CustomerData Get()
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, Name, Country FROM Customers"))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        CustomerData customers = new CustomerData();
                        sda.Fill(customers.CustomersTable);
                        return customers;
                    }
                }
            }
        }
    }
 
    public void Insert(string name, string country)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO Customers (Name, Country) VALUES (@Name, @Country)"))
            {
                cmd.Parameters.AddWithValue("@Name", name);
                cmd.Parameters.AddWithValue("@Country", country);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
 
    public void Update(int customerId, string name, string country)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("UPDATE Customers SET Name = @Name, Country = @Country WHERE CustomerId = @CustomerId"))
            {
                cmd.Parameters.AddWithValue("@CustomerId", customerId);
                cmd.Parameters.AddWithValue("@Name", name);
                cmd.Parameters.AddWithValue("@Country", country);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
 
    public void Delete(int customerId)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId"))
            {
                cmd.Parameters.AddWithValue("@CustomerId", customerId);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
}
 
VB.Net
Public Class Service
    Implements IService
    Public Function [Get]() As CustomerData Implements IService.Get
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using con As New SqlConnection(constr)
            Using cmd As New SqlCommand("SELECT CustomerId, Name, Country FROM Customers")
                Using sda As New SqlDataAdapter()
                    cmd.Connection = con
                    sda.SelectCommand = cmd
                    Using dt As New DataTable()
                        Dim customers As New CustomerData()
                        sda.Fill(customers.CustomersTable)
                        Return customers
                    End Using
                End Using
            End Using
        End Using
    End Function
 
    Public Sub Insert(name As String, country As String) Implements IService.Insert
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using con As New SqlConnection(constr)
            Using cmd As New SqlCommand("INSERT INTO Customers (Name, Country) VALUES (@Name, @Country)")
                cmd.Parameters.AddWithValue("@Name", name)
                cmd.Parameters.AddWithValue("@Country", country)
                cmd.Connection = con
                con.Open()
                cmd.ExecuteNonQuery()
                con.Close()
            End Using
        End Using
    End Sub
 
    Public Sub Update(customerId As Integer, name As String, country As String) Implements IService.Update
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using con As New SqlConnection(constr)
            Using cmd As New SqlCommand("UPDATE Customers SET Name = @Name, Country = @Country WHERE CustomerId = @CustomerId")
                cmd.Parameters.AddWithValue("@CustomerId", customerId)
                cmd.Parameters.AddWithValue("@Name", name)
                cmd.Parameters.AddWithValue("@Country", country)
                cmd.Connection = con
                con.Open()
                cmd.ExecuteNonQuery()
                con.Close()
            End Using
        End Using
    End Sub
 
    Public Sub Delete(customerId As Integer) Implements IService.Delete
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using con As New SqlConnection(constr)
            Using cmd As New SqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId")
                cmd.Parameters.AddWithValue("@CustomerId", customerId)
                cmd.Connection = con
                con.Open()
                cmd.ExecuteNonQuery()
                con.Close()
            End Using
        End Using
    End Sub
End Class
 
 
Adding Reference of WCF Service
The next task is to add the Service Reference of the WCF service to the project so that it can be used to populate the GridView.
1. Right Click the Project in the Solution Explorer and click Add Service Reference from the context menu.
Select Insert Edit Update Delete using WCF Service in ASP.Net
 
2. Then you need to locate the WCF Service in the project using the Discover button and then press OK to add its Service Reference.
Select Insert Edit Update Delete using WCF Service in ASP.Net
 
 
HTML Markup
The HTML Markup consists of an ASP.Net GridView with multiple event handlers assigned which will be discussed later.
The GridView has a CommandField column which will display the command buttons i.e. Edit, Update, Cancel and Delete.
Below the GridView there’s a Form which will allow us to insert data to the SQL Server database table using the WCF Service.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="CustomerId"
OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added.">
<Columns>
    <asp:TemplateField HeaderText="Name" ItemStyle-Width="150">
        <ItemTemplate>
            <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
        </EditItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
        <ItemTemplate>
            <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="txtCountry" runat="server" Text='<%# Eval("Country") %>'></asp:TextBox>
        </EditItemTemplate>
    </asp:TemplateField>
    <asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150"/>
</Columns>
</asp:GridView>
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse">
<tr>
    <td style="width: 150px">
        Name:<br />
        <asp:TextBox ID="txtName" runat="server" Width="140" />
    </td>
    <td style="width: 150px">
        Country:<br />
        <asp:TextBox ID="txtCountry" runat="server" Width="140" />
    </td>
    <td style="width: 100px">
        <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
    </td>
</tr>
</table>
 
 
Binding the GridView using WCF Service
The GridView is populated from the database inside the Page Load event of the page using the Get method of the WCF Service.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}
 
private void BindGrid()
{
    ServiceReference.ServiceClient client = new ServiceReference.ServiceClient();
    GridView1.DataSource = client.Get().CustomersTable;
    GridView1.DataBind();
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.BindGrid()
    End If
End Sub
 
Private Sub BindGrid()
    Dim client As New ServiceReference.ServiceClient()
    GridView1.DataSource = client.Get().CustomersTable
    GridView1.DataBind()
End Sub
 
Following is the GridView containing records.
Select Insert Edit Update Delete using WCF Service in ASP.Net
 
For the GridView I have set EmptyDataText to display message when no records are present.
Select Insert Edit Update Delete using WCF Service in ASP.Net
 
 
Inserting records using WCF Service
The following event handler is executed when the Add Button is clicked. The name and the country values are fetched from their respective TextBoxes and then passed to the Insert method of the WCF Service.
Finally the GridView is again populated with data by making call to the BindGrid method.
C#
protected void Insert(object sender, EventArgs e)
{
    ServiceReference.ServiceClient client = new ServiceReference.ServiceClient();
    client.Insert(txtName.Text.Trim(), txtCountry.Text.Trim());
    this.BindGrid();
}
 
VB.Net
Protected Sub Insert(sender As Object, e As EventArgs)
    Dim client As New ServiceReference.ServiceClient()
    client.Insert(txtName.Text.Trim(), txtCountry.Text.Trim())
    Me.BindGrid()
End Sub
 
 
Editing and Updating using WCF Service
Edit
When the Edit Button is clicked, the GridView’s OnRowEditing event handler is triggered. Here simply the EditIndex of the GridView is updated with the Row Index of the GridView Row to be edited.
C#
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    this.BindGrid();
}
 
VB.Net
Protected Sub OnRowEditing(sender As Object, e As GridViewEditEventArgs)
    GridView1.EditIndex = e.NewEditIndex
    Me.BindGrid()
End Sub
 
Update
When the Update Button is clicked, the GridView’s OnRowUpdating event handler is triggered.
CustomerId which is the primary key is fetched from the DataKey property of GridView while the Name and Country fields are fetched from their respective TextBoxes and are passed to the Update method of the WCF Service.
For more details on DataKeys please refer my article DataKeyNames in GridView example in ASP.Net.
 
C#
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridViewRow row = GridView1.Rows[e.RowIndex];
    int customerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
    string name = (row.FindControl("txtName") as TextBox).Text;
    string country = (row.FindControl("txtCountry") as TextBox).Text;
    CRUD_Service.ServiceCS service = new CRUD_Service.ServiceCS();
    service.Update(customerId, name, country);
    GridView1.EditIndex = -1;
    this.BindGrid();
}
 
VB.Net
Protected Sub OnRowUpdating(sender As Object, e As GridViewUpdateEventArgs)
    Dim row As GridViewRow = GridView1.Rows(e.RowIndex)
    Dim customerId As Integer = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Values(0))
    Dim name As String = TryCast(row.FindControl("txtName"), TextBox).Text
    Dim country As String = TryCast(row.FindControl("txtCountry"), TextBox).Text
    Dim client As New ServiceReference.ServiceClient()
    client.Update(customerId, name, country)
    GridView1.EditIndex = -1
    Me.BindGrid()
End Sub
 
Cancel Edit
When the Cancel Button is clicked, the GridView’s OnRowCancelingEdit event handler is triggered. Here the EditIndex is set to -1 and the GridView is populated with data.
C#
protected void OnRowCancelingEdit(object sender, EventArgs e)
{
    GridView1.EditIndex = -1;
    this.BindGrid();
}
 
VB.Net
Protected Sub OnRowCancelingEdit(sender As Object, e As EventArgs)
    GridView1.EditIndex = -1
    Me.BindGrid()
End Sub
 
Select Insert Edit Update Delete using WCF Service in ASP.Net
 
 
Deleting records using WCF Service
When the Delete Button is clicked, the GridView’s OnRowDeleting event handler is triggered.
CustomerId which is the primary key is fetched from the DataKey property of GridView and is passed to the Delete method of the WCF Service in order to delete the record.
C#
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
    int customerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
    CRUD_Service.ServiceCS service = new CRUD_Service.ServiceCS();
    service.Delete(customerId);
    this.BindGrid();
}
 
VB.Net
Protected Sub OnRowDeleting(sender As Object, e As GridViewDeleteEventArgs)
    Dim customerId As Integer = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Values(0))
    Dim service As New CRUD_ServiceVB.ServiceVB()
    service.Delete(customerId)
    Me.BindGrid()
End Sub
 
In order to display a confirmation message when deleting row, I have made use of OnRowDataBound event handler where I have first determined the Delete Button and then I have attach the JavaScript Confirm to its client side Click event handler.
C#
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
    {
        (e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
    }
}
 
VB.Net
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow AndAlso e.Row.RowIndex <> GridView1.EditIndex Then
        TryCast(e.Row.Cells(2).Controls(2), LinkButton).Attributes("onclick") = "return confirm('Do you want to delete this row?');"
    End If
End Sub
 
Select Insert Edit Update Delete using WCF Service in ASP.Net
 
 
Downloads