VorTex.Zerg
VorTex.Zerg

Reputation: 73

Breaking news in the top of the form

I have a form which in the top of it i put a label. In this label, whenever user open the program, this label will connect to the PasteBin Site. ( a site which you can paste or type whatever you want and at the end you can create a link about whatever you typed.) Now i could create a breaking news in the top of the form and it works great. But this will happen only once. let me put my code here first :

private void Form1_Load(object sender, EventArgs e)
{
    WebRequest.Create("http://pastebin.com/raw/vkABdKag");
    lblNews2.Text = new System.Net.WebClient().DownloadString("http://pastebin.com/raw/vkABdKag");
    lblNews2.ForeColor = System.Drawing.Color.White;
}

But this will happen only once. I mean even i change the text in this URL, again last text will be show. It seems that the program download the text only once and it will show it at the top of the form. Now this is my question. How can i put this code or what code should i add to this code, that whenever user open the program, first program check this link for if the text in this URL has been changed or not. Is it any code like : refresh or reload or ... for this function ? Thanks in advance for your answers.

Upvotes: 1

Views: 230

Answers (1)

TaW
TaW

Reputation: 54433

First put the download code into a separate function, so you can call it as needed:

string getNewsFrom(string url)
{
    string content = new System.Net.WebClient().DownloadString(url);
    return content;
}

Next pull a Timer component from the Toolbox onto the Form. Call it newsTimer. Set its Interval to a time you like.

newsTimer.Interval = 5 * 60 * 1000;   // set the timer to tick every 5 minutes

Doubleclick the Timer component and code the resulting Tick event:

private void newsTimer_Tick(object sender, EventArgs e)
{
    lblNews2.Text = getNewsFrom(yourUrl);
}

This assumes you have a class level variable yourUrl that holds the url you want to use.

If you want to, add a CheckBox to your Form and name it newsListening. Doubleclick it to create the CheckedChanged event and code it like this:

private void newsListening_CheckedChanged(object sender, EventArgs e)
{
    newsTimer.Enabled = newsListening.Checked;
    if (newsTimer.Enabled) newsTimer_Tick(null, null); do one download immediately!
}

If you want the timer to run all the time you can Start() it in the form_Load; if you want to use the CheckBox and start with the Timer running, trigger the CheckedChanged event by putting a newsListening_Checked = true; in the load event!

Now you will get the current content updated every five minutes and can start and stop the timer.

Note that you don't need a WebRequest when you use a WebClient.

Upvotes: 2

Related Questions