Lewis Mitchell
Lewis Mitchell

Reputation: 13

How to I condition a text box for a string if it holds a integer

I'm currently having some issues with error checking on a textbox. It holds a variable (called Price) as Double. Its purpose is to take a number in, and when a button is clicked it adds it to a running total displayed in a different textbox.

Now I have an error when checking if the textbox is empty using:

!string.IsNullOrWhiteSpace(txtAddItem.Text)

However, I'm unsure of how to error check if a string or character other than a number has been entered. Any ideas are appreciated.

Upvotes: 1

Views: 801

Answers (3)

Diado
Diado

Reputation: 2257

You can use Double.TryParse()

double number;
if (Double.TryParse(txtAddItem.Text, out number)) {
    Console.WriteLine("'{0}' is a valid double: {1}", value, number);
} else {
    Console.WriteLine("Unable to parse '{0}' as a valid double", value);
} 

Upvotes: 1

iSpain17
iSpain17

Reputation: 3053

Method 1: RegEx

You should try to use a regular expression. Regular expressions (Regex in short) are used to match strings against patterns. For example, if you only want to allow integers:

Regex r = new Regex(@"^[0-9]+$")

The Regex class has an .IsMatch(string s) method, where s is the string you want to test against the pattern.

Method 2: try-catch and Parse()

Another way to do it, which might be a bit more beginner-friendly, is a try-catch block. (I am assuming your TextBox's name is TextBox1 and you store the sum value in a runningSum variable.)

try {
    double x = double.Parse(TextBox1.Text);
    runningSum += x;
catch (ArgumentException ax) {
    //handle if it is not a number in the TextBox
}

Method 3: TryParse()

A more advanced version which combines try-catch and Parse() is using the double.TryParse() method which returns a true/false value based on whether conversion was successful or not.

double x;
if (double.TryParse(TextBox1.Text, out x)) {
    runningSum += x;
} else {
    //handle if it is not a number in the TextBox.
}

Upvotes: 3

Eifion
Eifion

Reputation: 5553

If the value needs to be a valid double you could use 'double.TryParse'. Something like:

if (double.TryParse(txtAddItem.Text, out double price) == false)
{
  // Show error or clear textbox
}
else
{
  // Value is valid, add to total
}

Upvotes: 1

Related Questions