如何自定义格式的 TextBox 输入? [英] How to TextBox inputs of custom format?

查看:31
本文介绍了如何自定义格式的 TextBox 输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何只允许以这种格式输入文本框?

How to allow inputs to the textbox in this format only?

推荐答案

所以你需要一个接受的 TextBox:

So you need a TextBox that accepts:

  • 一个或多个以逗号和/或...分隔的数字
  • 数字标记的范围,例如 1-5.
  • 每个数字/数字都应在最小值和最大值的范围内.

让我们为此创建一个自定义 TextBox.

Let's create a custom TextBox for that.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace YourNamespace
{
    [DesignerCategory("Code")]
    public class PrintPageRangeTB : TextBox
    {
        public PrintPageRangeTB() : base() { }
//...

覆盖 OnKeyPress 方法以接受 0-9- 除了 Control 键:

Override the OnKeyPress method to accept 0-9, , and - in addition to the Control keys:

//...
        protected override void OnKeyPress(KeyPressEventArgs e)
        {            
            if (!char.IsControl(e.KeyChar) 
                && !char.IsDigit(e.KeyChar) 
                && e.KeyChar != '-' 
                && e.KeyChar != ',')
                e.Handled = true;
            else
                base.OnKeyPress(e);
        }
//...

重写 OnTextChanged 方法以通过调用 IsValidInput() 函数来验证输入,并在函数返回 false 时删除最后输入的字符>:

Override the OnTextChanged method to validate the input by calling the IsValidInput() function and to delete the last entered character whenever the function returns false:

//...
        protected override void OnTextChanged(EventArgs e)
        {
            if (Text.Trim().Length > 0 && !IsValidInput())
                SendKeys.SendWait("{BS}");
            else
                base.OnTextChanged(e);
        }
//...

IsValidInput() 函数验证 Text 属性并使用 RegEx 检测任何无效格式.还要检查最小值和最大值.

The IsValidInput() function validates the Text property and detects any invalid format using RegEx. Also checks for the minimum and maximum values.

//...
        private bool IsValidInput() => IsValidInput(Text);

        private bool IsValidInput(string Input)
        {
            var parts = Input.Split(new[] { '-', ',' },
                StringSplitOptions.RemoveEmptyEntries);
            var pages = parts
                .Where(x => int.TryParse(x, out _)).Select(x => int.Parse(x));

            return Input.Trim().Length > 0
                && pages.Count() > 0
                && !parts.Any(x => x.Length > 1 && x.StartsWith("0")) 
                && !Regex.IsMatch(Input, @"^-|^,|--|,,|,-|-,|\d+-\d+-|-\d+-") 
                && !pages.Any(x => x < Min || x > Max);
        }
//...

添加用于分配最小值和最大值的属性、返回 Text 是否具有有效格式的属性以及返回所选数字/页数的属性..

Add properties to assign the minimum and maximum values, a property that returns whether the Text has a valid format, and a property that returns the selected numbers/pages..

//...
        public int Min { get; set; } = 1;
        public int Max { get; set; } = 1000;
        [Browsable(false)]
        public bool IsValidPageRange => IsValidInput();
        [Browsable(false)]
        public IEnumerable<int> Pages
        {
            get
            {
                var pages = new HashSet<int>();

                if (IsValidInput())
                {
                    var pat = @"(\d+)-(\d+)";
                    var parts = Text.Split(new[] { ',' }, 
                        StringSplitOptions.RemoveEmptyEntries);

                    foreach(var part in parts)
                    {
                        var m = Regex.Match(part, pat);

                        if (m != null && m.Groups.Count == 3)
                        {
                            var x = int.Parse(m.Groups[1].Value);
                            var y = int.Parse(m.Groups[2].Value);

                            for (var i = Math.Min(x, y); i <= Math.Max(x, y); i++)
                                pages.Add(i);
                        }
                        else if (int.TryParse(part.Replace("-", ""), out int v))
                            pages.Add(v);
                    }
                }
                return pages.OrderBy(x => x);
            }
        }
//...

加入选择并通过默认或传递的分隔符分隔它们的函数:

A function that joins the selection and separate them by the default or the passed separator:

//...
        public string PagesString(string separator = ", ") =>
            string.Join(separator, Pages);
    }
}

重建,从工具箱中删除一个PrintPageRangeTB,运行并尝试.

Rebuild, drop a PrintPageRangeTB from the Toolbox, run and try.

这里是完整代码.

相关

  • IP4 文本框.»
  • 这篇关于如何自定义格式的 TextBox 输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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