Question

I have a TextBox in which I wanna place a number, the program is supposed to read it, by converting it into a decimal, however, after performing the needed maths with the number, if I delete it from the TextBox, it immediatly produces an error:

Format exception was unhandled ( input string in a incorrect format)

this happens on the line on which I try to convert the text into a decimal

private void readW_TextChanged(object sender, EventArgs e)
{
    string _W = readW.Text;
    _Wd = Convert.ToDecimal(_W);
}
Was it helpful?

Solution

You get

Format exception was unhandled ( input string in a incorrect format)

because string.Empty cannot be converted to a decimal.

You can use TryParse to inform you if parsing fails:

bool success = decimal.TryParse(_W, out _Wd);
if (success) {
    // Use the result
}
else {
    // Depending on your needs, do nothing or show an error
}

Note that _W being string.Empty may be a condition you want to ignore, while other parse failures might warrant an error message. If so, your else might look like

else {
    if (!string.IsNullOrEmpty(_W)) ShowAnErrorMessageSomehow();
}

OTHER TIPS

Sounds like you're making it so the number can't be converted into a decimal. Unsurprisingly, this causes the conversion to fail. Try using Decimal.TryParse instead:

private void readW_TextChanged(object sender, EventArgs e)
{
    string _W = readW.Text;
    Decimal.TryParse(_W, out _Wd);
}

This will prevent the exception if the conversion fails. It will also return a bool, which you can use to perform other operations conditionally only when the conversion succeeds, e.g.:

private void readW_TextChanged(object sender, EventArgs e)
{
    string _W = readW.Text;
    if(Decimal.TryParse(_W, out _Wd))
    {
        Console.WriteLine("Valid decimal entered!");
    } 
}

Please try this code. But make sure that user can type only numbers in the textbox. Thanks.

private void readW_TextChanged(object sender, EventArgs e)
{
    string _W = readW.Text;
    _Wd = Convert.ToDecimal("0"+_W);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top