天天看点

C#如何获取天气情况?

使用Winform (C#)调用互联网上公开的WebServices(http://www.webxml.com.cn/WebServices/WeatherWebService.asmx)来实现天气预报,该天气预报 Web 服务,数据来源于中国气象局 http://www.cma.gov.cn/ ,数据每2.5小时左右自动更新一次,准确可靠。包括 340 多个中国主要城市和 60 多个国外主要城市三日内的天气预报数据。

方法:

 1、引入Web服务。在VS中项目上右击→添加服务引用。

2、在弹出的添加服务引用窗口,录入web服务地址和引用后的命名空间。

C#如何获取天气情况?

3、核心代码

Weather.www.WeatherWebService w = new Weather.WeatherWebService();
 string citynow = label9.Text.Trim();//获取当前城市
 if (label9.Text == "联网后点击文字重试!")
 {
 }else
 {
 string[] s = new string[23];//准备一个数组存放结果
 s = w.getWeatherbyCityName(citynow);
 label12.Text = s[6];
 }
           

报错处理

这行报“服务器无法处理请求。 ---> 未将对象引用设置到对象的实例。”

错误处理方法

 添加服务引用->高级->添加web服务引用

定义w对象时 用cn.com.webxml.www.WeatherWebService w = new cn.com.webxml.www.WeatherWebService();

cn.com.webxml.www是引用名。

C#如何获取天气情况?

原文:http://www.zhating.cn/index.php/post/87.html

更多C#文章:http://www.zhating.cn/index.php/category-4_2.html