Search code examples
c#winformstimerlabelmarquee

how to use a timer to make text move from side to side?


I have a label that I am trying to move side to side. I got it to work with a while (true) loop but decided to try and use a timer instead.

    private int x = 0;
    private int y = 11;
    private void timer1_Tick(object sender, EventArgs e)
    {
        if (x <= 11)
        {
            x++;
            string ping = new string(' ', x) + "ping";
            label2.Text = ping;
        }
        else if (y >= 0)
        {
            y--;
            string pong = new string(' ', y) + "pong"; // this is where the exceptions given
            label2.Text = pong;
        }

that is as far as I have gotten it works sorta but after it does it once it throw the exception

'count' must be non-negative.

I am not sure how to fix this any help would be great.


Solution

  • When y reaches 0, it will still be decremented one more time. Change to y > 0 and you should be ok.