How do I add a number to a label in C#?
So I want to have a number that can be added to but then written out in a label. I'm doing it in Visual C#.NET.
For example, if I had code like this (either in a timer or while loop):
int i = 0;
i = i + 5;
label4 = "Current Number of Views: " + i.ToString开发者_StackOverflow中文版();
I can't use ToString() to convert it to a string. So how would I make i displayable
While I don't understand why you can't use i.toString()
, I suppose that you could also use something like
label4.Text = String.Format("Current Number of Views: {0:d}", i);
This should yield the same result.
Edit: as @BiggsTRC points out (which I didn't think of), your error is probably a result of not assigning to the right variable. You probably should access the property label4.Text
to assign to. The code example fixes this properly now.
u could use String.Format without explicitly using ToString()
label4.Text = String.Format("Current Number of Views: {0}", i);
This should work. The one issue i see is the label itself. It should look like this:
label4.Text = "Current Number of Views: " + i.ToString();
I dont understand why cant you use i.ToString(). By default, i is assigned with 0 value and hence, i.ToString() would not throw any exception.
if you are using WPF , then you should assign the value to the content property of the label.
label4.Content = "Current Number of Views: " + i.ToString();
精彩评论