How to access a Web service from a C# Desktop Application

This project will teach you how to create a C# Desktop Application that uses a Web Service as its backend. You will need Visual Web Developer Express and Visual C# Express.


Step 1: Creating the Web Service

Open Visual Web Developer and go to File > New Project. Under Project Types select Visual C# > Web. Under Templates select ASP.NET Web Service Application. Press the Ok button.


By default, Visual Web Developer will create a Web Service and a HelloWorld operation (method) in it that returns a string.

In this example we will add another operation so we learn how to deal with parameters. Add the following code after the HelloWorld operation closing brace:

public int sum(int a, int b)
    return a + b;

Notice the [WebMethod] annotation. It lets Web Developer know we are adding a web operation and it must do all the required stuff to publish it.

We are now ready to run the web service, so press the start button ws2 and don’t stop it.

Visual Web Developer will open an Internet Explorer window that shows your Web Service description. Copy the URL you see there, since you will use it later. Don’t close Internet Explorer since that will stop your web service too!


Step 2: Creating the C# Desktop Application

Open Visual C# Express and go to File > New Project. Under Templates select Windows Forms Application and press Ok.


Now we will add a reference to our Web Service. In the Solution Explorer, right click on WindowsFormsApplication1 and select Add Service Reference


Paste de URL you copied from Internet Explorer in step 1 and press the Go button. If everything goes ok, you should see the HelloWorld and the sum operations listed in this window. Press Ok to continue.


You should now have a Reference to your Web Service in your Solution Explorer named ServiceReference1.



Now let’s go back to the Windows Form Designer. By default, Visual C# Express will create an empty Windows Form for you. Using the Toolbox add some controls so it looks like the following image:


Double click the button1 button and add the following code:

private void button1_Click(object sender, EventArgs e)
    ServiceReference1.Service1Soap s = new ServiceReference1.Service1SoapClient();
    label1.Text = "" + s.sum(int.Parse(textBox1.Text), int.Parse(textBox2.Text));

Click the start button ws2to start using your application… write some values in the text boxes and click the sum button. Your application will pass the parameters to the web service and will show you the result.