cdj
cdj

Reputation: 43

if number is greater in textbox

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

Answers (5)

user2509901
user2509901

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

hmnzr
hmnzr

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

sa_ddam213
sa_ddam213

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

Hanlet Escaño
Hanlet Escaño

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

djs
djs

Reputation: 230

Your if statement must be inside a function or the code won't compile.

Upvotes: 0

Related Questions