C# winform调用webservice天气预报

1.打开vs2008,新建一个c#下的project项目

点击选择windows Forms Application

命个名为 weathertest

2.这时候我们要设计窗体,设计窗体之前,我们研究一下网上的webservice会返回给我们什么。

输入网址,点击getWeatherbyCityName那个链接,进去后上面就有介绍的该方法该如何调用。

在测试那个文本框里输入一个城市名,比如:青岛  ,我们得到如下结果:

根据这个前一页的介绍,这个方法返回的是一个string数组,里面有23个元素,所以上图中每一个中间的元素就是数组的一个元素,这里我们就可以根据我们想要的数组元素来确定窗体的设计,我的设计如下:

Ok,设计完窗体,我们就开始研究如何调用网上的这个webservice啦。

3.回到vs2008,右键点击解决方案选择add service reference

在namespace里输入我们自己定义的名字,这里我叫它Weather,点一下GO,等如上图以后,点击ok,工具就会自动把这个webservice添加到项目中。这时我们会看到多了个这个:

这就说明到这步我们是正确的,接下来我们来编写调用它的代码:

4.双击我们设计的窗体上的按钮,在click事件中输入代码:

private void button1_Click(object sender, EventArgs e)

        {

          weathertest.Weather.WeatherWebService w = new weathertest.Weather.WeatherWebService("WeatherWebServiceSoap");

//把webservice当做一个类来操作

            string[] s = new string[23];//声明一个string数组存放其返回的结果

            string c = this.textBox2.Text.Trim();//获得文本框2的内容

            s = w.getWeatherbyCityName(c);

//以文本框内容为变量实现方法getWeatherbyCityName

           if (s[8] == "")

           {

                MessageBox.Show("暂时不支持您查询的城市");

            }

            else

            {

              //  pictureBox1.Image = Image.FromFile(@"d:\image\" + s[8] + "");

//将相应的值赋给相应的文本显示出来

               textBox1.Text = s[0];

            textBox3.Text = s[1];

            textBox4.Text = s[2];

            textBox5.Text = s[4];

            textBox6.Text = s[5];

            textBox7.Text = s[6];

            textBox8.Text = s[7];

            textBox9.Text = s[10];

            textBox10.Text = s[12];

            textBox11.Text = s[13];

            textBox12.Text = s[14];

            textBox13.Text = s[17];

            textBox14.Text = s[18];

            textBox15.Text = s[19];

            }

        }

输入完代码以后,运行。

你可能感兴趣的:(c#,开发语言)