I have two textboxes, I want to multiply their values.
In VB = Val(Text1.Text) * Val(Text2.Text)
What is it in C#?
Also, I don't know my version but I'm using 2008.
Printable View
I have two textboxes, I want to multiply their values.
In VB = Val(Text1.Text) * Val(Text2.Text)
What is it in C#?
Also, I don't know my version but I'm using 2008.
Try thisCode:int Text1Value = Convert.ToInt32(TextBox1.Text);
int Text2Value = Convert.ToInt32(TextBox2.Text);
intResult = Text1Value * Text2Value
int.Parse or double.Parse should do it.
If you need a one-liner...
C# Code:
double endVal = double.Parse(textBox1.Text) * double.Parse(textBox2.Text);
double.TryParse is more suitable when dealing with user input.
Thanks - What I was looking for.Quote:
Originally Posted by timeshifter
Try entering a non-numerical value into one of those textboxes;)Quote:
Originally Posted by Zach_VB6
Yes, anything but numbers and decimals will break it. The assumption was a controlled entry screen. If the user is dumb enough to enter "seven" into a text box labeled as "Money", then they deserve to have an app blow up in their face.
[/personal opinion]
If someone showed me an application that crashed for incorrect input, I'd never touch that application again.Quote:
Originally Posted by timeshifter
In a homework situation you can assume perfect input if the instructor says you can. In a real world situation you can never assume that the user will not enter invalid data. If a user enters "seven" instead of "7" then they're an idiot but I don't think the app crashing for that is appropriate. Also, I'm sure even timeshifter has hit the wrong key accidentally every now and again.
In VB the Val function will not throw an exception if the input is invalid. It just keeps reading digits until there are no more or it meets an invalid character. For that reason Val is bad because it may appear to work but use the wrong data. If data is entered that is obviously wrong then the user should be notified, not the data be ignored. For instance, if the user entered "12w34" then Val would return 12.0, which is obviously not what the user intended. You should be using TryParse in VB and C#:You should only use Convert.ToInt32 or Int32.Parse when you know for sure that the data is valid. You should almost never use Val.CSharp Code:
double num1; double num2; if (double.TryParse(this.textBox1.Text, num1) && double.TryParse(this.textBox2.Text, num2)) { MessageBox.Show((num1 * num2).ToString(), "Product"); } else { MessageBox.Show("Please enter valid numbers only.", "Invalid Input"); }
Hear hear. Exactly as it should be done.