【轉】Winform中textBox通過正則表達式限制只能輸入數字且是兩位小數

見代碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class FormFYSD : Form
    {
        public FormFYSD()
        {
            InitializeComponent();
        }

        private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
        {
            bool result = false;
            //判斷當前textBox是否爲空
            if (!string.IsNullOrEmpty(textBox3.Text.Trim()))
            {
                //Regex rex = new Regex(@"^[0-9]*$");
                Regex rexFull = new Regex(@"^[0-9]+(.[0-9]{0,1})?$");
                //判斷輸入是否是退格鍵
                if (e.KeyChar == '\b')
                {
                    result = false;
                }
                else
                {
                    //判斷是否匹配正則表達式
                    if (rexFull.IsMatch(textBox3.Text.Trim()) || rexFull.IsMatch(textBox3.Text.Trim() + e.KeyChar.ToString()))
                    {
                        //判斷字符串中小數點的位數
                        if (Regex.Matches(textBox3.Text.Trim() + e.KeyChar.ToString(), "\\.").Count == 2)
                        {
                            result = true;
                        }
                        else
                        {
                            //判斷輸入字符是否是數字或者小數點
                            if (!(char.IsNumber(e.KeyChar) || e.KeyChar == (char)('.')))
                            {
                                result = true;
                            }
                            else
                            {
                                result = false;
                            }
                        }
                    }
                    else
                    {
                        result = true;
                    }
                }
            }
            else
            {
                if (e.KeyChar < '0' || e.KeyChar > '9')//這是不允許輸入0-9數字
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
            }
            e.Handled = result;
        }
    }
}

這裏需要注意添加一個引用:using System.Text.RegularExpressions;否則Regex無法識別。

 

本文轉載自:https://jingyan.baidu.com/article/d3b74d640ff6cf1f77e6098f.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章