Reputation: 43
I am new to this so please be patient, I am having a bit of trouble with if statement.
I want to print a message in textbox 1 if textbox 2 is over 0.5. Can anyone help please.
class Product
{
public string collectmessage1()
{
return "Collect your product";
}
if (txtMoney.Text > 0.5)
{
Product cokecollect;
cokecollect = new Product();
txtProducts.Text = cokecollect.collectmessage1();
}
Upvotes: 3
Views: 306
Reputation:
TextBox.Text
property returns a String
which cannot be compared to a 0.5
, a double
object. Using your code will throw an error
Error1 Operator '>' cannot be applied to operands of type 'string' and 'double'
Parse the string returned by the text property of your textbox to double before comparing and you will get rid of this error. As Velous said, TryParse is a better choice in case of a format exception.
double no;
bool valid = double.TryParse(txtMoney.Text, out no);
if (valid && no > 0.5) {
Product cokecollect;
cokecollect = new Product();
txtProducts.Text = cokecollect.collectmessage1();
}
Upvotes: 6
Reputation: 1430
Try this:
if (decimal.Parse(txtMoney.Text) > 0.5m)
{
Product cokecollect;
cokecollect = new Product();
txtProducts.Text = cokecollect.collectmessage1();
}
To prevent exceptions when you money format is incorrect, you can use decimal.TryParse
method instead:
decimal money = 0m;
decimal.TryParse(txtMoney.Text, out money);
if (money > 0.5m)
{
Product cokecollect;
cokecollect = new Product();
txtProducts.Text = cokecollect.collectmessage1();
}
Upvotes: 1
Reputation: 43596
You can use double.TryParse
to parse the string
to a double
double result = 0.0;
if (double.TryParse(txtMoney.Text, out result) && result > 0.5)
{
Product cokecollect;
cokecollect = new Product();
txtProducts.Text = cokecollect.collectmessage1();
}
Upvotes: 3
Reputation: 17380
Since it is a TextBox
and you are allowing input from the users, I would personally use double.TryParse
instead of double.parse
double myNumber;
bool isValid = double.TryParse(textBox1.Text, out myNumber);
if (isValid)
{
if (myNumber > 0.5)
{
...
}
}
This way if the user inputs something bad (letters for instance) you do not get an exception.
Upvotes: 1