• C# WinForm 文本框只能输入带两位小数的数字


    之前的做法是:

    if (!(char.IsNumber(e.KeyChar) || e.KeyChar == '\b' || e.KeyChar == (char)('.')))
    {
    e.Handled
    = true;
    }

    但这种方式存在一些问题,例如可以输入两个小数。。。

    后来改用正则表达式加上面的代码来处理:

    先using:

    using System.Text.RegularExpressions;

    代码:

    private void amountTextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
    if (Convert.ToInt32(e.KeyChar) == 8)
    {
    e.Handled
    = false;
    }
    else
    {
    Regex rex
    = new Regex(@"^[0-9.]*$"); //初始化正则表达式(检测每次输入的字符)
    Regex rexFull = new Regex(@"^[0-9]+(.[0-9]{0,1})?$"); //初始化正则表达式(检测所有已经输入的字符)
    if (rexFull.IsMatch(this.amountTextBox.Text.Trim()) || rexFull.IsMatch(this.amountTextBox.Text.Trim() + e.KeyChar.ToString()))
    {
    if (Regex.Matches(this.amountTextBox.Text.Trim() + e.KeyChar.ToString(), "\\.").Count == 2) //防止输入两个小数点
    {
    e.Handled
    = true;
    }
    else
    {
    if (!(char.IsNumber(e.KeyChar) || e.KeyChar == '\b' || e.KeyChar == (char)('.')))
    {
    e.Handled
    = true;
    }
    else
    {
    e.Handled
    = false;
    }
    }
    }
    else
    {
    e.Handled
    = true;
    }
    }
    }

    这样可以解决问题,但依然存在一个之前也存在的问题,那就是当文本框没内容时,鼠标点其他地方都没任何反应,类似于假死。。。

    没办法,只好加个默认值了:

    private void amountTextBox_TextChanged(object sender, EventArgs e)
    {
    if (string.IsNullOrEmpty(this.amountTextBox.Text.Trim()))
    {
    this.amountTextBox.Text = "20";
    this.amountTextBox.SelectAll();
    }
    else if (this.amountTextBox.Text.Trim().Substring(0, 1) == ".")
    {
    this.amountTextBox.Text = this.amountTextBox.Text.Trim().Substring(1, this.amountTextBox.Text.Trim().Length - 1);
    }
    }

    到这里面问题基本上都解决了,但感觉太麻烦了,不知道大家有没有更好的解决方法!

  • 相关阅读:
    「实战」攻防中钓鱼上线MAC终端
    JAVA审计SQL注入
    使用Netcat实现通信和反弹Shell
    通过Mssql提权的几种姿势
    第三方提权之ServU提权
    使用LCX进行内网端口转发
    Proxifier/ProxyChains+reGeorg组合进行内网代理
    通过Mysql提权的几种姿势
    java:文件与IO
    java:常用类库api
  • 原文地址:https://www.cnblogs.com/mic86/p/1831913.html
Copyright © 2020-2023  润新知