Convert Integer to String (for textbox)

imchris

New member
Joined
Mar 2, 2017
Messages
2
Programming Experience
Beginner
Hi.

I'm using Visual Studio 2015 Community to write the following simple codes in C# (windows form):

int myNumber = 25;
txtTextBox1.Text = myNumber;


I would get a syntax error as follow: "Cannot implicitly convert type int to string."

I understand why I was getting the above error because I didn't have the ToString() method at the end.

But if I rewrote the second line as follow, I did not get a syntax error:

txtTextBox1.Text = txtTextBox1.Text + myNumber;

The number 25 in the textbox just fine.

All I did was I added the second "txtTextBox1.Text" (highlighted in red above). But how come I didn't have to use ToString() at the end?

Thanks,
 
In both those code snippets, you are assigning something to a property of type String so the object you assign has to be a String. The first snippet generates an error because the object on the right is not a String. The second snippet does not generate an error so that means that whatever is on the right IS a String, i.e. this expression:
txtTextBox1.Text + myNumber

results in a String. What you're doing there is invoking the addition operator with two operands. The addition operator is defined for some types and combinations of types and not others. In this case, the operands are of type String and Int32 and the operator is defined for that combination. The implementation first calls ToString on the Int32 and then concatenates that with the other operand. So, you see, ToString MUST be used in both cases but, in the second case, it is implicit in the addition operator when the operands are type String and Int32. If you were to use two operands of type Int32 then you'd be back to square one because the result of that would be another Int32 so you'd have to perform the conversion to type String yourself.
 
jimcil, thanks for the great in-depth explanation.

The reason I was using the second snippets was because I was using a FOR loop to print several integer numbers in an array (into the same textbox). This way all of the numbers will be displayed in the textbox. If I had used the first snippets, only the last number would be displayed in the textbox. Anyhow, thanks for the clear explanation!
 
Changing a property of a control repeatedly in a loop is never a good idea. If you want the final Text value to be a String that you build in a loop then that's exactly what you should do, i.e. build a String in a loop and make one assignment to the Text property with that String when the loop is done.
 
Back
Top Bottom