只允许在文本框小数点后两位数字? [英] Only allow two digits after decimal in textbox?

查看:93
本文介绍了只允许在文本框小数点后两位数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用户在其中输入数字的文本框,但我怎样才能让这个如果他们键入'。'后,只允许2位小数?



 私人无效textBox1_KeyPress(对象发件人,KeyPressEventArgs E)
{
如果(char.IsControl(e.KeyChar)
和!&安培; !char.IsDigit(e.KeyChar)
和;&安培;!'。'e.KeyChar =)
{
e.Handled = TRUE;
}

//只允许一个小数点
如果(e.KeyChar ==
和'。';及(发件人为文本框)。文本。的IndexOf('。')-1)〜
{
e.Handled = TRUE;
}
}


解决方案

刚添加:

 如果(Regex.IsMatch(textBox1.Text,@\.\d\d)) {
e.Handled = TRUE;
}

要你的函数


的结束

I have a textbox where the user enters a number, but how can i make it so that if they type the '.' after it it only allows 2 decimal places?

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (!char.IsControl(e.KeyChar)  
        && !char.IsDigit(e.KeyChar)  
        && e.KeyChar != '.') 
    { 
        e.Handled = true; 
    } 

    // only allow one decimal point 
    if (e.KeyChar == '.'  
        && (sender as TextBox).Text.IndexOf('.') > -1) 
    { 
        e.Handled = true; 
    } 
}

解决方案

Just add:

if (Regex.IsMatch(textBox1.Text, @"\.\d\d")) {
   e.Handled = true;
}

to the end of your function

这篇关于只允许在文本框小数点后两位数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆