In Focus

How to use a Web Service in Windows Form Application

This blog describes how to Communicate with a web service in Windows Form application.

Introduction

This blog describes how to Communicate with a web service in Windows Form application.

In previous article we saw How to Create a Simple Web Service and Use it in ASP.Net.

Now here I am going to use that same service in Windows Form application.

Creating the client application

Now create a Windows Form Application and design your form as in the following screen.

index.jpg

Add a web reference to the Application
 
Go to Solution Explorer then select the solution then click on "Add Service Reference". it will open an window

Then click on Advanced button on that window.

index1.jpg

A new window will open. then click on "Add Web Reference".

index2.jpg
A new window will open. Then within the URL type the service reference path.

(For example: http://localhost:65312/WebServiceSample/Airthmatic.asmx) then click on the "Go" button.

Nowyou will see your service methods. Change the web reference name from "localhost" to any other name as you like (for example: Airthmatic).

Click on the "Add Reference" button. It will create a Proxy at the client side.

index3.jpg 
Now go to the cs code and add a reference for the Service.

Write the following code.

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 WindowsAirthmatic

{

    public partial class Form1 : Form

    {

        Airthmatic.Airthmatic obj = new Airthmatic.Airthmatic();

        int a, b, c;

        public Form1()

        {

            InitializeComponent();

        }

        private void btnAdd_Click(object sender, EventArgs e)

        {

            a = Convert.ToInt32(textBox1.Text);

            b = Convert.ToInt32(textBox3.Text);

            c = obj.Add(a, b);

            label4.Text = c.ToString();

        }

        private void btnSub_Click(object sender, EventArgs e)

        {

            a = Convert.ToInt32(textBox1.Text);

            b = Convert.ToInt32(textBox3.Text);

            c = obj.Sub(a, b);

            label4.Text = c.ToString();

        }

        private void btnMul_Click(object sender, EventArgs e)

        {

            a = Convert.ToInt32(textBox1.Text);

            b = Convert.ToInt32(textBox3.Text);

            c = obj.Mul(a, b);

            label4.Text = c.ToString();

        }

        private void btnDiv_Click(object sender, EventArgs e)

        {

            a = Convert.ToInt32(textBox1.Text);

            b = Convert.ToInt32(textBox3.Text);

            c = obj.Div(a, b);

            label4.Text = c.ToString();

        }

    }

}

Now first run the Web service then the application.


index3.png