ARTICLE

WCF Service to Connect Between Windows Forms Application and SQL Database

Posted by Rohatash Kumar Articles | WCF with C# July 26, 2012
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.
Reader Level:

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:

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.SqlClient;

using System.Data;

 

namespace WCFServiceForInsert

{

    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.

    [ServiceContract]

    public interface IService1

    {

        [OperationContract]

        string InsertUserDetails(UserDetails userInfo);

 

        [OperationContract]

        DataSet  SelectUserDetails();

      }

 

    // Use a data contract as illustrated in the sample below to add composite types to service operations.

    [DataContract]

    public class UserDetails

    {

        int userid;

        string username;

        string password;

        string country;

        string email;

 

        [DataMember]

        public int UserID

        {

            get { return userid; }

            set { userid = value; }

        }

 

        [DataMember]

        public string UserName

        {

            get { return username; }

            set { username = value; }

        }

        [DataMember]

        public string Password

        {

            get { return password; }

            set { password = value; }

        }

        [DataMember]

        public string Country

        {

            get { return country; }

            set { country = value; }

        }

        [DataMember]

        public string Email

        {

            get { return email; }

            set { email = value; }

        }

    }

}

Service.svc.cs File

In this file we define the definition of the function InsertUserDetails(UserDetails userInfo).

And replace the code with the following:

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.SqlClient;

using System.Data;

 

namespace WCFServiceForInsert

{

    // 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

    {

 

        public DataSet SelectUserDetails()

        {

            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=registration;User ID=sa;Password=wintellect");

            con.Open();

            SqlCommand cmd = new SqlCommand("Select * from RegistrationTable", con);

            SqlDataAdapter sda = new SqlDataAdapter(cmd);

            DataSet ds = new DataSet();

            sda.Fill(ds);

            cmd.ExecuteNonQuery();

            con.Close();

            return ds;

        }

 

        public string InsertUserDetails(UserDetails userInfo)

        {

            string Message;

            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=registration;User ID=sa;Password=wintellect");

            con.Open();

            SqlCommand cmd = new SqlCommand("insert into RegistrationTable(UserName,Password,Country,Email) values(@UserName,@Password,@Country,@Email)", con);

            cmd.Parameters.AddWithValue("@UserName", userInfo.UserName);

            cmd.Parameters.AddWithValue("@Password", userInfo.Password);

            cmd.Parameters.AddWithValue("@Country", userInfo.Country);

            cmd.Parameters.AddWithValue("@Email", userInfo.Email);

            int result = cmd.ExecuteNonQuery();

            if (result == 1)

            {

                Message = userInfo.UserName + " Details inserted successfully";

            }

            else

            {

                Message = userInfo.UserName + " Details not inserted successfully";

            }

            con.Close();

            return Message;

        }

    }

}

 

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:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

namespace WindowsFormsApplication1

{

    public partial class Registration : Form

    {

        ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client(); // Add service reference

      

        public Registration()

        {

            InitializeComponent();

            showdata();

        }

 

        private void showdata()  // to show the data in the DataGridView

        {

            DataSet   ds = new DataSet();

            ds = obj.SelectUserDetails();

            dataGridView1.DataSource = ds.Tables[0];

            dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

           ServiceReference1 .UserDetails  objuserdetail=new ServiceReference1.UserDetails(); // add type reference

            objuserdetail .UserName =textBoxUserName.Text ;

              objuserdetail.Password  =textBoxPassword.Text ;

            objuserdetail .Country =textBoxCountry .Text ;

            objuserdetail .Email =textBoxEmail .Text ;

            obj.InsertUserDetails(objuserdetail);

            showdata(); 

        }

    }

}

 

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

Article Extensions
Contents added by trung quang on Nov 25, 2012
Thank  Rohatash Kumar for your guides

i only typed your project but i have a trouble with "run the application
<in my attach picture>
fault1.JPG

please check for me!

thank alot Sir!
COMMENT USING

Trending up