user3708761
user3708761

Reputation: 275

Label Text Refresh every second

I'm trying to make a label refresh every second so the countdown updates, having some trouble. I'm extremely new to C# apologies for the noob questions.

private void Form1_Load(object sender, EventArgs e)
{
    bool ephCD = true;
    int ephHours = (DateTime.Today.AddDays(1) - DateTime.Now).Hours;
    int ephMinu = (DateTime.Today.AddDays(1) - DateTime.Now).Minutes;
    int ephSecs = (DateTime.Today.AddDays(1) - DateTime.Now).Seconds;

    label1.Text = ephHours.ToString() + ":" + ephMinu.ToString() + ":" + ephSecs.ToString();

    while (ephCD == true)
    {
        label1.Refresh();
    }
}

When launching this the program doesn't even appear.

Why does the program not appear?

Upvotes: 3

Views: 10254

Answers (4)

alansiqueira27
alansiqueira27

Reputation: 8506

I ended up with this simpler solution:

<script>
        var myTimer = setInterval(Atualizar, 20000);

        function Atualizar() {
            __doPostBack('UpdatePanelNew', '');
        }
    </script>

Make sure you wrap what you want to update within an UpdatePanel.

This code will request a postback in every 20s. So in the code behind I can do this:

protected void Page_Load(object sender, EventArgs e)
    {
        myLabel.InnerText = GetInDatabaseTheValueIwant();
    }

Upvotes: 0

Darien Pardinas
Darien Pardinas

Reputation: 6186

This will do, just copy and paste:

    private void Form1_Load(object sender, EventArgs e)
    {
        // To update the first time.
        label1.Text = (DateTime.Today.AddDays(1)- DateTime.Now).ToString(@"hh\:mm\:ss");
        var timer = new Timer {Interval = 1000};
        timer.Tick += (o, args) =>
        {
            label1.Text = (DateTime.Today.AddDays(1)- DateTime.Now).ToString(@"hh\:mm\:ss");
        };
        timer.Start();
    }

Upvotes: 1

pollirrata
pollirrata

Reputation: 5286

Updating the label in a while statement is not a good option, a better approach would be to use Timer class

    var aTimer = new System.Timers.Timer(1000);
    aTimer.Elapsed += OnTimedEvent;
    aTimer.Enabled = true;


private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
    //update the label
}

Upvotes: 1

BradleyDotNET
BradleyDotNET

Reputation: 61349

You are performing an infinite loop in Form_Load. This means that the form will never finish loading, and your program will be stuck.

Your refresh loop needs to be on a separate thread, or ideally toss the loop and use a Timer instead of spin locking the CPU on an infinite loop.

Timer myTimer = new Timer(1000);
void Form1_Load()
{
     myTimer.Elapsed += UpdateLabel;
     myTimer.Start();
}

private void UpdateLabel(object sender, ElapsedEventArgs e)
{
    //Update label here
}

Upvotes: 7

Related Questions