c# - TextBox with Numeric Input -
i working on database application , using class validate numeric numbers on keypress event of textbox.
the numbers may have (-) negative values fixed decimal places (third parameter dplaces) e.g. 10000, -1000, 12345.45, -12345.45
after adding decimal, not able edit other digits although without decimal working perfectly.
thanks in advance
public static class util { public static void numinput(object sender, keypresseventargs e, int dplaces) { if (!char.iscontrol(e.keychar) && !char.isdigit(e.keychar) && e.keychar != '.' && (e.keychar != '-')) { e.handled = true; } // allow 1 decimal point if (e.keychar == '.' && (sender textbox).text.indexof('.') > -1) { e.handled = true; } var = (sender textbox).selectionlength; // allow minus sign @ origin var x = (sender textbox).text.indexof('-'); if (e.keychar == '-' && (sender textbox).text.indexof('-') > 0) { e.handled = true; } if (!char.iscontrol(e.keychar)) { textbox textbox = (textbox)sender; if (textbox.text.indexof('.') > -1 && textbox.text.substring(textbox.text.indexof('.')).length >= dplaces + 1) { e.handled = true; } } } }
its because of logical operation in if block comparing length =3 , char = '.'.
change lastly part of code : (edit : handle issue of inserting text before '.')
if (!char.iscontrol(e.keychar)) { textbox textbox = (textbox)sender; // position of new char inserted int position = textbox.selectionstart; if (textbox.text.indexof('.') > -1 && position > textbox.text.indexof('.')) // check location of new char if(!(textbox.text.substring(textbox.text.indexof('.')).length <= dplaces + 1)) { e.handled = true; } } this job..!!!
edit : next stop copy/past in textbox
textbox.shortcutsenabled = false; c# winforms textbox
No comments:
Post a Comment