Anonymous
Anonymous

Reputation: 59

C# How to Fix Error: 'Input string was not in a correct format.' in Textbox

In the code below, I'm trying to validate the Textbox (txt_quantity and txt_discount)

But instead of getting this MessageBox.Show("Cannot be empty"); I'm getting the error of

('Input string was not in a correct format.')

Did i forgot something here?

Upvotes: 0

Views: 2521

Answers (1)

Handbag Crab
Handbag Crab

Reputation: 1538

Use a NumericUpDown instead of a textbox to capture integer/decimal values. It handles all the validation for you stopping users from entering non-numeric values. You can set the maximum and minimum values you require and you don't have to worry about no values being entered as the NumericUpDown will always have a default value.

If you're using integers then you just need to cast to an int when you retrieve the value, otherwise it returns a decimal. So your code would be:

Quantity = Convert.ToInt32(numericupdown1.Value);
Discount = numericupdown2.Value;

If you're hellbent on using textboxes then you need to remove whitespace with .Trim()

Quantity = Convert.ToInt32(txt_quantity.Text.Trim());

And use int.TryParse instead;

int value = 0;
if (int.TryParse(txt_quantity.Text.Trim(), out value)
{
    // Successful conversion so value now contains your integer
}

You can do the same with decimals.

Upvotes: 2

Related Questions