Reputation: 13
I have the following scenario.I am using App.config in Winforms and I have a value that is set to int (In settings). I want to use this value as a label text. Am I correct that labels can only display string values? This is what I have done here but not getting expected result (value to the label):
int ExclRate = Properties.Settings.Default.PriorExclTimer;
string ExclTime = ExclRate.ToString();
ExclTime = label60.Text;
PriorExclTimer is the type of the value in app.config.
I can make this work if I set the value in app.config to string, but that means I would have to convert from string to int in a much more sensitive part of the program, and I would rather not have to do that if possible. This is that line that works:
label60.Text = Properties.Settings.Default.PriorExclTimer;
I'm very new to C#, so I am really feeling my way around. Thanks...
Upvotes: 0
Views: 17294
Reputation: 13
This works for me:
int ExclRate = Properties.Settings.Default.PriorExclTimer;
label60.Text = ExclRate.ToString();
Many thanks for the insights on this topic. I will be manipulating data to and from a string a good bit for the project I am working on...
Upvotes: 0
Reputation: 1
int ExclRate = Properties.Settings.Default.PriorExclTimer;
label60.Text = ExclRate.ToString();
Code above will give you exception if PriorExclTimer
is null or empty. So better you use int.TryParse
to assign it to int. Not in this case, but ToString
does not handle the null
case, it gives exception. So you should try Convert.ToString
instead.
While doing string manipulations you have to take care of culture and case (string case sensitive or insensitive)
Upvotes: 0
Reputation: 30255
In C# you cannot directly assign int
to string
. It has to always undergo conversion (either parse string to integer, or get a string out of integer).
As you say it's better to convert integer to a string for display purposes. Labels cannot directly show integer, so you will always need to convert it, or write some wrapper class if it's not enough.
Be aware that ToString()
is culture specific, i.e. it will use the culture from the current thread. It might or might not be what you want. If you want InvariantCulture
you can use ToString(CultureInfo.InvariantCulture)
.
P.S. As mentioned in the comments you can do various tricks like ExclRate + ""
, or in C#6 ${ExclRate}
, but they are all basically converting an integer to string. I guess they all call ToString()
inside.
Upvotes: 3