Wednesday, February 15, 2012

Display Yahoo weather using ASP.Net



Show Yahoo weather using ASP.Net 

Step 1)Open a AJAX enable ASP.NET page in Visual Studio.

Step 2) Add following code in your ASP.Net page.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Yahoo_weather.aspx.cs" Inherits="Yahoo_weather" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id="Head1" runat="server">
    <title>Yahoo AJAX Weather Example</title>
    <style>
   
        #WeatherUpdatePanel { font-family:Tahoma; font-size:11px;  }

    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <asp:Timer ID="Timer" runat="server"  OnTick="Tick" Interval="1000" />
                    <asp:Panel ID="WeatherUpdatePanel" runat="server" />
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>


Step 3) Add below code in code behind of your ASP.Net page

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Data;
using System.Xml;

public partial class Yahoo_weather : System.Web.UI.Page
{
    protected void Tick(object sender, EventArgs e)
    {

        string RSS = "http://weather.yahooapis.com/forecastrss?w=2502265";
        //Change w value to get your location ...

        XmlDocument xDoc = new XmlDocument();
        xDoc.Load(RSS);

        XmlNodeList ItemList = xDoc.GetElementsByTagName("item");
        string Title = ItemList[0].SelectSingleNode("title").InnerText;
        string Description = ItemList[0].SelectSingleNode("description").InnerText;

        WeatherUpdatePanel.Controls.Add(new LiteralControl("<p>" + Title + "</p>"));
        WeatherUpdatePanel.Controls.Add(new LiteralControl("<p>" + Description + "</p>"));

    }
}


3 comments:

  1. I tried this, but error returned: "WeatherUpdatePanel is not found in the current context". How would you fix that?

    Thank you

    ReplyDelete
  2. this error occurred because you didn't place a panel control with id 'WeatherUpdatePanel'.

    ReplyDelete
  3. who can i add code for different countries and their cities. ?

    ReplyDelete