Jess Chan
Jess Chan

Reputation: 439

How do I change the value of the label every tick event C# .NET

I am trying to make a "blinking" type of effect in my C# project, by that I mean that I want a label to switch text every tick.. And I've come to mind that the easiest way to do this would be by using a timer event to change the label text every tick once the start button is being pressed. This is a WinForm Application

But I dont know how to make the label switch values after every tick

I think I am making this harder than it should be..

What my code does now is that it tries to change the myLabel1 to firstBlinkName; AND secondBlinkName; at the same time.. I would like some time in between, I really dont know how to do this.

private void nameBlinkInterval_Tick(object sender, EventArgs e)
{
    var firstBlinkName = nameBlinkFirstName.Text;
    var secondBlinkName = nameBlinkSecond.Text;
    myLabel1.text = firstBlinkName;
    myLabel1.text = secondBlinkName;
}

Sorry for bad naming conventions!

Upvotes: 0

Views: 644

Answers (3)

Huntt
Huntt

Reputation: 185

myLabel1.Text = "firstText";

private void nameBlinkInterval_Tick(object sender, EventArgs e)
{
    if(myLabel1.Text == "firstText")
    {
        myLabel1.Text = "secondText";
    }
    else
    {
        myLabel1.Text = "firstText";
    }
}

Just check if the labels contains the firstText and if that is true, set the label to the secondText. If the label doesn't contain the firstText anymore the second Tick, it puts the label back to firstText.

Upvotes: 0

TaW
TaW

Reputation: 54433

This will test, change each time and refresh the label:

private void nameBlinkInterval_Tick(object sender, EventArgs e)
{
   var firstBlinkName = nameBlinkFirstNameTextBox.Text;
   var secondBlinkName = nameBlinkSecondTextBox.Text;

   labelThatWillBlink.Text =  labelThatWillBlink.Text  == firstBlinkName ?
                              secondBlinkName  : firstBlinkName ;
   labelThatWillBlink.Refresh();
}

Note the use of the ternary operator!

Upvotes: 2

sujith karivelil
sujith karivelil

Reputation: 29006

I'm not sure, I'm i get you correctly, If your requirement is to toggle some text on the label in each Tick. If so you should keep one global variable that will increase its value in each Tick. Following code will help you

int tikCount=0; // This will be a global variable
string firstBlinkName = "some string Here";
string secondBlinkName = "Some other string";
private void nameBlinkInterval_Tick(object sender, EventArgs e)
{
    labelThatWillBlink = tikCount++ %2 ==0? firstBlinkName:secondBlinkName;
   // then do something here that will switch the labelThatWillBlink's value to secondBlinkName

}

Upvotes: 1

Related Questions