Omar AlMadani
Omar AlMadani

Reputation: 201

Make Label visible for 5 seconds in winforms

I am creating a WinForms application in visual studio 2017.

I have a Login form where, if the user enters a wrong username or password, a label that has the property visible = false, becomes visible for 5 seconds and the goes back for being not visible.

I have tried to do something like this:

label3.Visible = true;
Thread.Sleep(3000);
label3.Visible = false;

Obviously, this doesn't work, I couldn' find anyone with a very similar problem online, so I hope you could help me with this.

I have seen other soloutions using this:

var t = new Timer();
t.Interval = 3000; // it will Tick in 3 seconds
t.Tick += (s, e) =>
{
    label3.Hide();
    t.Stop();
};
t.Start();

but I get an error saying "a local or parameter named 'e' cannot be declared in this scope because that name is used in an enclosing local scope to define a local parameter".

Upvotes: 3

Views: 3319

Answers (2)

Tiber Septim
Tiber Septim

Reputation: 335

if you're using .NET Framework 4.5 or above, you can also have done it with this code:

label3.Visible = true;
System.Threading.Tasks.Task.Delay(3000).ContinueWith(_ =>
{
    Invoke(new MethodInvoker(()=> { label3.Visible = false; }));
});

Upvotes: 6

Ipsit Gaur
Ipsit Gaur

Reputation: 2927

Rename e to some other variable as the error says you are already having a local variable named e in the scope.

var t = new Timer();
t.Interval = 3000; // it will Tick in 3 seconds
t.Tick += (s, event) =>
{
    label3.Hide();
    t.Stop();
};
t.Start();

Upvotes: 3

Related Questions