Assign numeric values to Textboxes
Beginner question:
I want to do some math during runtime and assign the result to a textbox.
I'm having TYPE problems.
For example:
double dValue1;
double dValue2;
txtMyTexBox.Text = dValue1 * dValue2 / 4.67;
Now I know you can't do this because the textbox is expecting a String. I'm just not sure how to do this correctly.
This doesn't work:
txtMyTexBox.Text = (string)(dValue1 * dValue2 / 4.67);
I'm still at the "Hello World" stage in C sharp coming from a VB6 background.
Help?
thx.
Re: Assign numeric values to Textboxes
Hello! All objects expose the ToString() method (and most output something useful when it is called) which returns a string representation or description of the object. In your case, use:
Code:
double dValue1;
double dValue2;
double result = dValue1 * dValue2 / 4.67;
txtMyTexBox.Text = result.ToString();
The more concise version works too:
Code:
double dValue1;
double dValue2;
txtMyTexBox.Text = (dValue1 * dValue2 / 4.67).ToString();
Make sense?
Re: Assign numeric values to Textboxes
Yes.
The first example I knew. It is that having to create an extra variable to hold the value first just seemed like a waste as I have been used to doing without in VB.
The second example, however, I didn't know you could do.
Interesting.
Thank you. :)
Re: Assign numeric values to Textboxes
Quote:
having to create an extra variable to hold the value first just seemed like a waste
I always recommend writing for maximum clarity. Defining an extra variable or not is not likely to impact performance. The compiler will automatically optimize code, so defining the variable or not is unlikely to impact performance in any way.
Of course, in this case, both are about equally informative.
Re: Assign numeric values to Textboxes
True.
I'm all for clarity.
If you can achieve that in less lines though, that's preferable. :)