c# - How to aill cause it to ces when I try to d -
my program crashes when try decimal calculation starting decimal point. example, ".9" cause crash whereas "0.9" works fine.
here's code:
private void textbox1_keypress(object sender, keypresseventargs e) { if (!char.iscontrol(e.keychar) && !char.isdigit(e.keychar) && (e.keychar != '.')) { e.handled = true; } if ((e.keychar == '.') && ((sender textbox).text.indexof('.') > -1)) { e.handled = true; } if (e.keychar == convert.tochar(keys.return)) { textbox2.text = area1.tostring(); } } private void textbox1_textchanged(object sender, eventargs e) { if (textbox1.text == string.empty) { textbox2.text = " "; } else diameter1 = double.parse(textbox1.text); area1 = (math.pi * math.pow((diameter1 / 2), 2)); }
as updating value while typing, fail when have typed period , textbox contains "."
. when parse that, cause exception.
use tryparse
attempt parse value, , else if parsing fails. example:
private void textbox1_textchanged(object sender, eventargs e) { if (textbox1.text == string.empty) { textbox2.text = " "; } else { if (double.tryparse(textbox1.text, out diameter1)) { area1 = math.pi * math.pow((diameter1 / 2), 2); textbox2.text = area1.tostring(); } else { textbox2.text = "-not numeric-"; } } }
Comments
Post a Comment