-3

This really suprised me. One of the simplest things doesn't work, making a counter. I'm making a kinda game application in c# and there is also a timer who counts the time. Very simple right? I know how to code this and this is something I did before but I don't understand why it isn't working now.

int i = 0;
i++;
label1.Text = i.ToString();

label1.Text turns in to 1 and nothing else happens. Also tryied this with a timer but it freeezes in 1. I know this post isn't really going to help other people but it is very frustrating.

Emre
  • 29
  • 10
  • what do you want from it, its simply working '0+1 = 1' and every time you entered it initialize i=0 and increment 1 in it. – Mohammad Tayyab Apr 02 '17 at 13:03
  • Thats because every time you call this bit of code, you set i to 0 then increment to 1, the third line the value of i will always be 1. – Nick is tired Apr 02 '17 at 13:03
  • And what should happen here? You declare a local variable and initialize it to zero, next you increment it to 1 and next you set the text of the label to 1. You can call this code thousands times but the result will always be 1. If you want to be helped a lot more of code and context is required. – Steve Apr 02 '17 at 13:03

2 Answers2

2

Why you are always getting 1 in your label1 text?

The reason is very simple, each time you are getting to the first line, i is 0:

// Line 1
int i = 0;  // declaring and setting i to 0
// Line 2
i++;        // incrementing i to 1 
// Line 3
label1.Text = i.ToString();  // displaying i (which is equal to 1)

and then again you are getting to the Line 1 and setting i=0, etc...

I presume you have a UI application (win form, web form etc...) You already mentioned you have a timer that works fine and a label where you output the incremented i variable.

As already commented in order to see a change in your label you can use a loop as following:

int length = 100;  // for example
for (int i = 0; i < length; i++)
{
    label1.Text = i.ToString();
}

The output in label1 text will be 0, then 1, then 2 .... and finally 99. Obviously you won't be able to see all those values except the last one 99 at run-time but you can debug and see how it works.

I presume, what you needed is to have your label text changing each time the timer will tick. Following a code example how you could implement it:

private int i = 0; // initialized once in this UI class

private void timer1_Tick(object sender, EventArgs e)
{
    label1.Text = i.ToString();
    i++; // will increment by one each time the timer is ticking
}

Set your timer interval to ~1000 so you could clearly see how your text label increments at run-time.

ehh
  • 3,412
  • 7
  • 43
  • 91
1

If you want to increment it you have to add the incrementing logic in a loop like for or while loop:

If you want to use timer to count something please refer to this question : here

Community
  • 1
  • 1
Rey
  • 3,663
  • 3
  • 32
  • 55