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);
}
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();
}