Home > database >  Why the timer is not showing the dots on the label as text each time less one?
Why the timer is not showing the dots on the label as text each time less one?

Time:12-20

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Extract
{
    public partial class LoadingLabel : Label
    {
        private int TimeToCount = 300;
        private int Interval = 1000;
        private System.Windows.Forms.Timer _timer;
        private int counter = 0;

        public LoadingLabel()
        {
            InitializeComponent();

            this.Font = new Font("Arial", 14, FontStyle.Bold);

            StartCountDownTimer(Interval, true);
        }

        public void StartCountDownTimer(int Interval, bool EnableTimer)
        {
            _timer = new System.Windows.Forms.Timer
            {
                Interval = Interval,
                Enabled = false
            };

            _timer.Enabled = EnableTimer;

            _timer.Tick  = (sender, args) =>
            {
                if (counter == 0)
                {
                    this.Text = ".";
                    Thread.Sleep(3);
                    counter  ;
                }

                if(counter == 1)
                {
                    this.Text = "..";
                    Thread.Sleep(3);
                    counter  ;
                }

                if(counter == 2)
                {
                    this.Text = "...";
                    Thread.Sleep(3);
                    counter = 0;
                }
            };
        }
    }
}

The interval is set to 1000 one second.

I want to use the interval so each second it will add another dot starting from one dot to three. Then in the end when there are three dots start over again from one.

I tried for testing using a Thread.Sleep but it's not working it's showing only the last three dots and that's it.

CodePudding user response:

In the _timer.Tick your ifs are running sequentially.
You could replace 2nd and 3rd ifs with else if or replace your code with the following:

if (counter == 3)
{
    this.Text = "";
    counter = 0;
}
this.Text  = ".";
Thread.Sleep(3);
counter  ;

Also you could eliminate the counter field since its value is always equal to the Text.Length.

CodePudding user response:

Try a simple solution:

public Form1()
{
    InitializeComponent();
    Text = "";
    timer = new System.Windows.Forms.Timer
    {
       Interval = 1000
    };
    timer.Tick  = Timer_Tick;
    timer.Start();
}

private void Timer_Tick(object? sender, EventArgs e)
{
    if (Text.Contains("..."))
    {
       Text = "";
    }
    else
    {         
       Text  = ".";
    }
}
  • Related