C#二次控件中正则表达式应用

实现效果:

1,创建一个Winform项目

2,创建一个类库

3,类库中添加一个组件类

4,组件类中拖放一个ErrorProvider组件

MyTextBox代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
//添加正则表达式所用的引用
using System.Text.RegularExpressions;
using System.Threading.Tasks;
//添加引用
using System.Windows.Forms;


namespace ClassLibrary1
{
    public partial class MyTextBox : TextBox
    {
        public MyTextBox()
        {
            InitializeComponent();
        }

        public MyTextBox(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }
        //利用正则表达式判断是不是数字
        public int IsNumber(string Msg, string info)
        {
            Regex regex = new Regex(Msg, RegexOptions.IgnoreCase);
            if (!regex.IsMatch(info))
            {
                errorProvider1.SetError(this, "不允许输入数字以外的其他数值");
                return 1;
            }
            else
            {
                errorProvider1.SetError(this, string.Empty);
                return 0;
            }

        }
    }
}
View Code

Form1代码

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

namespace 二次控件
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //利用KeyUp事件
        private void MyTextBox1_KeyUp(object sender, KeyEventArgs e)
        {
            string Msg = "^[0-9]*$";
            int Result = myTextBox1.IsNumber(Msg, this.myTextBox1.Text.Trim());
        }
    }
}
View Code

注:Form1窗体中的TextBox控件是由MyTextBox生成后拖放的。

猜你喜欢

转载自www.cnblogs.com/Luck1996/p/12014751.html