WCF Service to Connect Between Windows Forms Application and SQL Database

Today, I have provided an article showing you how to insert and display data in a DataGridView control using a WCF service from C# code.

Today, I have provided an article showing you how to insert and display data in a DataGridView control using a WCF service from C# code. To insert and display data in a DataGridView control using a WCF service, we must do the following 3 things:
  1. Create Database Table
  2. Create WCF Service
  3. Create Windows Forms Application
In the first step we will create a table in SQL Server; after that we create a simple function to insert and display data in a DataGridView control using a WCF service. In a web application, add a reference for the service to insert and display data in the DataGridView control. Let's take a look at a practical example. The example application is developed in Visual Studio 2010 and SQL Server 2008.
 

Step 1: Creating Database Table

  1. Database name:  Registration
  2. Database table name: RegistrationTable
RegistrationTable Table
 
image1.jpg
 

Step 2: Creating WCF Service

 
Now you have to create a WCF Service:
  • Go to Visual Studio 2010
  • New-> Select a project
image2.jpg
 
Now click on the project and select WCF Service Application and provide a name for the service:
 
image3.jpg
 
Now click on the Ok Button. Then you will get 3 files in Solution Explorer.
  1. IService.cs
  2. Service.svc
  3. Service.svc.cs
The following image shows the following files:
 
image4.jpg 
 
For inserting data into the database you need to write the following code in the IService1.cs file which contains the two sections:
  1. OperationContract
  2. DataContract
The OperationContract section is used to add service operations and a DataContract is used to add types to the service operations.
 
Iservice1.cs File
 
Now we create a function in the OperationContract section of the Iservice1.cs file:
  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.SqlClient;  
  9. using System.Data;  
  10.   
  11. namespace WCFServiceForInsert  
  12. {  
  13.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.  
  14.     [ServiceContract]  
  15.     public interface IService1  
  16.     {  
  17.         [OperationContract]  
  18.         string InsertUserDetails(UserDetails userInfo);  
  19.         [OperationContract]  
  20.         DataSet  SelectUserDetails();  
  21.       }  
  22.      // Use a data contract as illustrated in the sample below to add composite types to service operations.  
  23.     [DataContract]  
  24.     public class UserDetails  
  25.     {  
  26.         int userid;  
  27.         string username;  
  28.         string password;  
  29.         string country;  
  30.         string email;  
  31.         [DataMember]  
  32.         public int UserID  
  33.         {  
  34.             get { return userid; }  
  35.             set { userid = value; }  
  36.         }  
  37.         [DataMember]  
  38.         public string UserName  
  39.         {  
  40.             get { return username; }  
  41.             set { username = value; }  
  42.         }  
  43.         [DataMember]  
  44.         public string Password  
  45.         {  
  46.             get { return password; }  
  47.             set { password = value; }  
  48.         }  
  49.         [DataMember]  
  50.         public string Country  
  51.         {  
  52.             get { return country; }  
  53.             set { country = value; }  
  54.         }  
  55.         [DataMember]  
  56.         public string Email  
  57.         {  
  58.             get { return email; }  
  59.             set { email = value; }  
  60.         }  
  61.     }  
  62. }  
Service.svc.cs File
 
In this file we define the definition of the function InsertUserDetails(UserDetails userInfo).
 
And replace the code with the following:
  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.SqlClient;  
  9. using System.Data;  
  10.   
  11. namespace WCFServiceForInsert  
  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.         public DataSet SelectUserDetails()  
  17.         {  
  18.             SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=registration;User ID=sa;Password=wintellect");  
  19.             con.Open();  
  20.             SqlCommand cmd = new SqlCommand("Select * from RegistrationTable", con);  
  21.             SqlDataAdapter sda = new SqlDataAdapter(cmd);  
  22.             DataSet ds = new DataSet();  
  23.             sda.Fill(ds);  
  24.             cmd.ExecuteNonQuery();  
  25.             con.Close();  
  26.             return ds;  
  27.         }  
  28.         public string InsertUserDetails(UserDetails userInfo)  
  29.         {  
  30.             string Message;  
  31.             SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=registration;User ID=sa;Password=wintellect");  
  32.             con.Open();  
  33.             SqlCommand cmd = new SqlCommand("insert into RegistrationTable(UserName,Password,Country,Email) values(@UserName,@Password,@Country,@Email)", con);  
  34.             cmd.Parameters.AddWithValue("@UserName", userInfo.UserName);  
  35.             cmd.Parameters.AddWithValue("@Password", userInfo.Password);  
  36.             cmd.Parameters.AddWithValue("@Country", userInfo.Country);  
  37.             cmd.Parameters.AddWithValue("@Email", userInfo.Email);  
  38.             int result = cmd.ExecuteNonQuery();  
  39.             if (result == 1)  
  40.             {  
  41.                 Message = userInfo.UserName + " Details inserted successfully";  
  42.             }  
  43.             else  
  44.             {  
  45.                 Message = userInfo.UserName + " Details not inserted successfully";  
  46.             }  
  47.             con.Close();  
  48.             return Message;  
  49.         }  
  50.     }  
  51. }  
Testing the Service
 
Press F5 to run the service. A WCF Test Client form will be displayed and it will load the service.
 
image5.jpg
 
Now double-click the InserUserDetails() method under IService1. The InserUserDetails tab will be displayed.
 
image22.jpg
 
The service was added successfully.
 
Now open the service in the browser.
 
Now right-click on the service1.vcs -> open in browser:
 
image6.jpg
 
Now copy the URL.
 
image8.jpg
 
URL
 
http://localhost:2268/Service1.svc
 

Step 3: Create Windows Forms Application (Accessing the Service)

 
Now, you have to create a windows Forms Application.
  • Go to Visual Studio 2010
  • New-> Select a project-> Windows Forms Application
  • Click OK
img1.jpg
 
Now add a new page to the website:
  • Go to the Solution Explorer
  • Right-click on the Project name
  • Select add new item
  • Add new windows form and give it a name
  • Click OK
img2.jpg
 
Now again go to the Solution Explorer and click on the add the service reference.
 
img3.jpg
 
The following window will be opened:
 
img4.jpg
 
Now paste the above URL in the address and click on the "Go" button:
 
img5.jpg
 
Click on the Ok Button. Now the reference has been added in the Solution Explorer.
 
img6.jpg
 
Now create a new Windows Form and drag and drop controls onto the Windows Form. The designing form looks like below:
 
img7.jpg
 
Double-click on the "Save" button, and add the following code with the click event handler:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9.   
  10. namespace WindowsFormsApplication1  
  11. {  
  12.     public partial class Registration : Form  
  13.     {  
  14.         ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client(); // Add service reference  
  15.         public Registration()  
  16.         {  
  17.             InitializeComponent();  
  18.             showdata();  
  19.         }  
  20.         private void showdata()  // to show the data in the DataGridView  
  21.         {  
  22.             DataSet   ds = new DataSet();  
  23.             ds = obj.SelectUserDetails();  
  24.             dataGridView1.DataSource = ds.Tables[0];
  25.             dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);  
  26.         }  
  27.         private void button1_Click(object sender, EventArgs e)  
  28.         {  
  29.             ServiceReference1.UserDetails  objuserdetail=new ServiceReference1.UserDetails(); // add type reference  
  30.             objuserdetail.UserName =textBoxUserName.Text ;  
  31.             objuserdetail.Password  =textBoxPassword.Text ;  
  32.             objuserdetail.Country =textBoxCountry .Text ;  
  33.             objuserdetail.Email =textBoxEmail .Text ;  
  34.             obj.InsertUserDetails(objuserdetail);  
  35.             showdata();   
  36.         }  
  37.     }  
  38. }  
Now run the application. 
 
Press CTRL+F5 to run the application.
 
img8.jpg
 
Now enter the UserName, Password, country and Email and click on the save Button.
 
img9.jpg
 
Now click on the save Button. Data will be saved in the database table and also displayed in the DataGridView on the form.
 
img10.jpg
 
Data has been inserted into the SQL Server database table and check it.
 
img11.jpg