Question

I am having trouble in trying to check if the textbox's text IsNumeric or not. Here is my code and I'm not too sure what has gone wrong:

        using Microsoft.VisualBasic;
        // ......
        bool result = Information.IsNumeric(textBox1 || textBox2.Text);

        if ( result == true)
        {
            decimal val1 = Convert.ToDecimal(textBox1.Text);
            decimal val2 = Convert.ToDecimal(textBox2.Text);
            textBoxAns.Text = (val1 + val2).ToString();
        }
        else
        {
            MessageBox.Show("Please enter a number", "Error");
        }
Was it helpful?

Solution

I don't understand this line:

Information.IsNumeric(textBox1 || textBox2.Text)

Probably you are getting an error something like:

Cannot apply operator ' || ' to operands of type TextBox and string

In C# you can use decimal.TryParse, it returns false if value is invalid:

decimal value1, value2;

if(decimal.TryParse(textBox1.Text, out value1) 
   && decimal.TryParse(textBox2.Text, out value2))
{
    textBoxAns.Text = (value1 + value2).ToString();
}

OTHER TIPS

You are looking for Decimal.TryParse(); In your example it would be something like this:

    private void button1_Click(object sender, EventArgs e)
    {
        decimal d1, d2 = 0;
        bool isFirstNumber = Decimal.TryParse(textBox1.Text, out d1);
        bool isSecondNumber = Decimal.TryParse(textBox2.Text, out d2);

        if (isFirstNumber && isSecondNumber)
        {
            textBoxAns.Text = (d1 + d2).ToString();
        }
        else
        {
            MessageBox.Show("Please enter a number", "Error");
        }
    }

I assume you have not added a reference to the Microsoft.VisualBasic-dll.

enter image description here

How to: Add or Remove References

Apart from that, your code does not make much sense. I guess you want to check if both values are numeric, then you need to use IsNumeric on both TextBox.Text values:

bool txt1Numeric = Information.IsNumeric(textBox1.Text);
bool txt2Numeric = Information.IsNumeric(textBox2.Text);

if (txt1Numeric && txt2Numeric)
{
    decimal val1 = Convert.ToDecimal(textBox1.Text);
    decimal val2 = Convert.ToDecimal(textBox2.Text);
    textBoxAns.Text = (val1 + val2).ToString();
}
else
{
    MessageBox.Show("Please enter a number", "Error");
}

You probably were going to say:

bool result = Information.IsNumeric(textBox1.Text) &&
              Information.IsNumeric(textBox2.Text);

Then it's going to work, but you will be parsing your values twice, one to check that's it's a numeric, and then another time to actually check what's there. Duplication can be avoided using Decimal.TryParse, as mentioned in other answers here.

As a side note, always look for a C# equivalent before sticking with VB.NET constructs in C# code. There is a high chance referencing VB.NET namespace & references is not needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top