C# Label shows Weather Information

Win95 Dev 1 Reputation point
2021-07-30T18:49:16.577+00:00

Hey
I want to create a simple weather app. A Label should show if its cloudy or sunny or rain and all the other things and the temperature in celsius. But because im a noob i dont know. So please help. Thanks

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,838 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,196 Reputation points
    2021-07-30T20:33:58.997+00:00

    There is replacement for a paid service for obtaining this information although the following will be good enough. I did not do the image aspect.

    https://github.com/karenpayneoregon/windows-forms-csharp/tree/master/OpenWeatherMapApp

    • Requires Json.Net
    • Code below does not show required classes which are included.

    Form code

    using System;
    using System.Net.Http;
    using System.Windows.Forms;
    using Newtonsoft.Json;
    using OpenWeatherMapApp.Classes;
    
    namespace OpenWeatherMapApp
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private async void GetButton_Click(object sender, EventArgs e)
            {
                var http = new HttpClient();
    
                /*-------------------------------------
                 * Set up to your long lat for your area
                 -------------------------------------*/
    
                var url = "https://forecast.weather.gov/MapClick.php?lat=44.9429&lon=-123.0351&FcstType=json";
    
                http.DefaultRequestHeaders.Add(
                    "User-Agent", 
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 " + 
                         "(KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36");
    
                var response = await http.GetAsync(url);
    
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    var weather = JsonConvert.DeserializeObject<WeatherRoot>(json);
    
    
                    weatherLabel.InvokeIfRequired(label =>
                    {
                        label.Text = $"{weather.Current.Temperature} degrees, {weather.Current.Weather}";
                    });
                }
            }
        }
    }
    
    0 comments No comments

  2. Castorix31 81,831 Reputation points
    2021-07-31T12:03:52.8+00:00

    If you want weather from your current location, you must first get Latitute/Longitude, then you can read the weather from "tile-service.weather.microsoft.com"

    A test =>

    119591-weather.jpg

    using System.Xml;  
    // Add reference to : System.Device  
    using System.Device.Location;  
      
    public partial class Form1 : Form  
    {  
        public Form1()  
        {  
            //InitializeComponent();  
            this.Load += new System.EventHandler(this.Form1_Load);  
        }  
      
        private void button1_Click(object sender, EventArgs e)  
        {  
            // https://learn.microsoft.com/en-us/dotnet/api/system.device.location.geocoordinate.latitude?view=netframework-4.8  
            GeoCoordinateWatcher watcher;  
            GeoCoordinate coordinate = null;  
            watcher = new GeoCoordinateWatcher();  
            watcher.PositionChanged += (sender1, e1) =>  
            {  
                coordinate = e1.Position.Location;  
                watcher.Stop();  
                if (coordinate != null)  
                {  
                    string sLocation = null;  
                    string sTemperature = null;  
                    string sWeather = null;  
      
                    double nLatitute = coordinate.Latitude;  
                    double nLongitude = coordinate.Longitude;  
                    XmlTextReader reader = null;  
                    try  
                    {  
                        string sLatitute = nLatitute.ToString().Replace(",", ".");  
                        string sLongitude = nLongitude.ToString().Replace(",", ".");  
                        string sAddress = String.Format("https://tile-service.weather.microsoft.com/livetile/front/{0},{1}", sLatitute, sLongitude);  
                        int nCpt = 0;  
                        reader = new XmlTextReader(sAddress);  
                        reader.WhitespaceHandling = WhitespaceHandling.None;                        
                        while (reader.Read())  
                        {  
                            if (reader.NodeType == XmlNodeType.Text)  
                            {  
                                if (nCpt == 0)  
                                    sLocation = reader.Value;  
                                else if (nCpt == 1)  
                                    sTemperature = reader.Value;  
                                else if (nCpt == 2)  
                                    sWeather = reader.Value;  
                                nCpt++;  
                            }                          
                        }  
                    }  
                    finally  
                    {  
                        if (reader != null)  
                            reader.Close();  
                    }  
                    string sTemperatureF = sTemperature.Replace("°", "");  
                    double nTemperatureC = (Double.Parse(sTemperatureF) -32.0)*(double)5/9;  
                    string sTemperatureC = nTemperatureC.ToString("#.#");  
                    label1.Text = String.Format("{0}, {1}F({2}°C), {3}", sLocation, sTemperature, sTemperatureC, sWeather);  
                }  
            };  
            watcher.Start();          
        }  
      
        private System.Windows.Forms.Button button1;  
        private System.Windows.Forms.Label label1;  
        private void Form1_Load(object sender, EventArgs e)  
        {  
            this.button1 = new System.Windows.Forms.Button();  
            this.label1 = new System.Windows.Forms.Label();  
      
            this.button1.Location = new System.Drawing.Point(40, 76);  
            this.button1.Name = "button1";  
            this.button1.Size = new System.Drawing.Size(75, 23);  
            this.button1.Text = "Get infos";  
            this.button1.UseVisualStyleBackColor = true;  
            this.button1.Click += new System.EventHandler(this.button1_Click);  
      
            this.label1.AutoSize = true;  
            this.label1.Location = new System.Drawing.Point(130, 81);  
            this.label1.Name = "label1";  
            this.label1.Size = new System.Drawing.Size(115, 13);  
            this.label1.Text = "[Location, T°, weather]";  
      
            this.Name = "Form1";  
            this.ClientSize = new System.Drawing.Size(425, 182);  
            this.Controls.Add(this.label1);  
            this.Controls.Add(this.button1);  
        }  
    }