这个有一些问题
先输入整数部分后再把整数部分删除,变相地让小数点跑到第一位
在两位小数的情况下如果选中两位小数也无法更改
网友 ymwcwee 已更正 请大家参考他的代码
<p><textarea cols="50" rows="15" name="code" class="c-sharp">/// <summary>
http://blog.csdn.net/jzz870519/archive/2010/08/08/5796876.aspx,因为我在他上面回复代码总是失败,所以自己开了。。。
- private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
- {
- if (char.IsNumber(e.KeyChar) || e.KeyChar == '.' || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Delete)
- {
- e.Handled = false; //让操作生效
- int j = 0; //记录小数点个数
- int k = 0; //记录小数位数
- int dotloc = -1; //记录小数点位置
- bool flag = false; //如果有小数点就让flag值为true
- //
- //去除首位是0的判断,因为我们不知道用户的意图,或许ta下次要在小数点前面输入数字。
- /*
- if (textBox1.Text.Length == 0)
- {
- if (e.KeyChar == '.')
- {
- e.Handled = true;
- }
- }
- */
- //
- for (int i = 0; i < textBox1.Text.Length; i++)
- {
- if (textBox1.Text[i] == '.')
- {
- j++;
- flag = true;
- dotloc = i;
- }
- if (flag)
- {
- if (char.IsNumber(textBox1.Text[i]) && e.KeyChar != (char)Keys.Back && e.KeyChar != (char)Keys.Delete)
- {
- k++;
- }
- }
- if (j >= 1)
- {
- if (e.KeyChar == '.')
- {
- if (textBox1.SelectedText.IndexOf('.') == -1)
- e.Handled = true; //输入“.”,选取部分没有“.”操作失效
- }
- }
- if (!flag) //此处控制没有小数点时添加小数点是否满足两位小数的情况
- {
- if (e.KeyChar == '.')
- {
- if (textBox1.Text.Length - textBox1.SelectionStart - textBox1.SelectedText.Length > 2) //the condition also can be instead of "textBox1.Text.Substring(textBox1.SelectionStart).Length-textBox1.SelectionLength>2"
- e.Handled = true;
- }
- }
- if (k == 2)
- {
- if (textBox1.SelectionStart > textBox1.Text.IndexOf('.') && textBox1.SelectedText.Length == 0 && e.KeyChar!
- =(char)Keys.Delete && e.KeyChar!=(char)Keys.Back) //如果已经有两位小数,光标在小数点右边,
- e.Handled = true;
- }
- }
- }
- else
- {
- e.Handled = true;
- }
- }
</textarea></p>