我将从代码开始
I will start with the code
private void textBox2_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '.' && !textBox2.Text.Contains(".") || e.KeyChar == '\b') { if (textBox2.Text.Contains(".")) { string[] txt = textBox2.Text.Split('.'); if (txt[1].Length > 1) { if (e.KeyChar >= '0' && e.KeyChar <= '9') { e.Handled = true; } } } else { e.Handled = false; } } else { e.Handled = true; } }解释: Basicaly它的作用:当有人输入时对于textBox2它只允许插入数字符号,退格和一个点(。),它还定义如果插入点,则只能在其后插入两个数字。 问题:当我输入数字示例时。 5.22 ir aby其他有点和两个数字之后,然后我选择鼠标数字5并删除它,我不能把任何数字输入它,因为有.22按照规定的规则不允许任何新的插入。 在这种情况下,我应该如何更改此代码以允许在点的左侧插入数字?有什么建议?
Explain: Basicaly what it does: when someone types to textBox2 it lets insert only numeric symbols, backspace and one dot (.), it also defines that if dot is inserted there can only be inserted two numbers after it. The problem: When I enter digit example. 5.22 ir aby other with dot and two number after it, then i selec with mouse digit 5 and delete it, I can''t put any number insted it, because there is .22 which by stated rules does not allow any new insertions. How should I change this code to allow insert numbers to left side of dot in such situation? Any suggestions?
推荐答案你几乎从不真正需要舍入。相反,当您在scree上显示数字时,应该使用正确的字符串格式。请参阅: msdn.microsoft/en-us /library/kfsatb94.aspx [ ^ ], msdn.microsoft/en -us / library / dwhawy9k.aspx [ ^ ], msdn.microsoft /en-us/library/0c899ak8.aspx [ ^ ]。 顺便说一下,它比明确的舍入更安全。如果您不小心在计算中使用舍入值,该怎么办?这可能导致计算结果不正确;很难找到这样的错误。
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { string[] txt = null; if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '.' && !textBox1.Text.Contains(".") || e.KeyChar == '\b') { if (textBox1.Text.Contains(".")) { txt = textBox1.Text.Split('.'); if (txt[1].Length > 1) { if (e.KeyChar >= '0' && e.KeyChar <= '9') { e.Handled = true; } } if (txt[0].Length != leftlen) { if (e.KeyChar >= '0' && e.KeyChar <= '9') { e.Handled = false; } else { e.Handled = true; } } } else { e.Handled = false; } } else { e.Handled = true; } if (txt != null) { leftlen = txt[0].Length; } }
大部分你想要的东西都在这个完成 只需在全局声明leftlen并在表单加载时将其初始化为-1 希望它能解决您的问题:)
Most of the things you want is done in this Just declare leftlen globally and initialize it on form load to -1 Hope it will solve your problem :)
更多推荐
将'十进制四舍五入到dot'后输入texBox问题
发布评论