c# - How to prevent 'System.FormatException' occurred in mscorlib.dll' with an empty textbox? -
i have programmed simple program me work out amount of carbohydrate per meal (i have diabetes) , issue system.formatexception
when 1 of textboxes empty.
how may prevent please ?
my code (using form consisting of 3 textboxes; 2 of require input me , third shows result of simple equation).
public partial class form1 : form { public form1() { initializecomponent(); } private void form() { tbccg.textchanged += textboxchanged; tbctg.textchanged += textboxchanged; } private void textboxchanged(object sender, eventargs e) { decimal carbst; decimal carbsperc = convert.todecimal(tbccg.text); decimal totcarbs = convert.todecimal(tbctg.text); carbst = carbsperc / 100 * totcarbs; tbtc.text = carbst.tostring("###,###.00"); } }
you can verify text in text boxes
if (string.isnullorwhitespace(tbccg.text)) tbccg.text = "0"; if (string.isnullorwhitespace(tbctg.text)) tbctg.text = "0"; decimal carbsperc = convert.todecimal(tbccg.text); decimal totcarbs = convert.todecimal(tbctg.text);
but if don't have kind of restrictions on text box try using decimal.tryparse
.
Comments
Post a Comment