限制在C#中的文本框输入小数的最佳方式 [英] Best way to limit textbox decimal input in c#

查看:155
本文介绍了限制在C#中的文本框输入小数的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让一个文本框在其中只能输入一个像12.00或1231231.00或123123



我在一个很长的路要走这样做,我。'M寻找最佳和最快的方式。



另外,小数点分隔符必须是特定文化的:

  Application.CurrentCulture.NumberFormat.NumberDecimalSeparator 


解决方案

这是一个相当简单的操作。你将需要过滤你不想出去的键,然后执行一些额外的检查



下面的代码添加到文本框的KeyDown事件:

 私人无效TextBox1_KeyDown(对象发件人,
System.Windows.Forms.KeyEventArgs E)
{
开关(e.KeyCode){
情况下Keys.D0:
情况下Keys.D1:
情况下Keys.D2:
情况下Keys.D3:
案Keys.D4:
情况下Keys.D5:
情况下Keys.D6:
情况下Keys.D7:
情况下Keys.D8:
情况下Keys.D9:
情况下Keys.NumPad0:
情况下Keys.NumPad1:
情况下Keys.NumPad2:
情况下Keys.NumPad3:
情况下Keys.NumPad4:
钥匙的情况下.NumPad5:
情况下Keys.NumPad6:
情况下Keys.NumPad7:
情况下Keys.NumPad8:
情况下Keys.NumPad9:
//允许数字只有在没有修饰符是主动
如果(e.Control || e.Alt || e.Shift){
//抑制与修饰
e.SuppressKeyPress =真正的数字;
e.Handled = TRUE;
Interaction.Beep();
}
中断;
的情况下(键)110:
案Keys.OemPeriod:(!。((文本框)发送方).Text.Contains())
如果{
//允许关键时期,如果没有'。
//在文本和无修饰符是活动
如果(e.Control || e.Alt || e.Shift){
//抑制与修饰
e.SuppressKeyPress =真正的数字;
e.Handled = TRUE;
Interaction.Beep();
}
}其他{
e.SuppressKeyPress = TRUE;
e.Handled = TRUE;
Interaction.Beep();
}
中断;
情况下Keys.Subtract:
情况下Keys.OemMinus:
如果(((文本框)发送方).SelectionStart == 0安培;&安培;
((文本框)发送方) .Text.Contains( - )){
//允许仅当光标
//是在文本框
//的开始和有在无弊负极键文本框
//并没有修饰符是活动的
如果(e.Control || e.Alt || e.Shift){
//抑制与修饰
é号码。 SuppressKeyPress = TRUE;
e.Handled = TRUE;
Interaction.Beep();
}
}其他{
e.SuppressKeyPress = TRUE;
e.Handled = TRUE;
Interaction.Beep();
}
中断;
情况下Keys.C:
情况下Keys.X:
情况下Keys.V:
情况下Keys.Z:
//允许复制,剪切,粘贴和放大器;通过检查
//的状态CTRL撤消。
如果(e.Control == FALSE){
e.SuppressKeyPress = TRUE;
e.Handled = TRUE;
Interaction.Beep();
}
中断;
情况下Keys.Control:
情况下Keys.ControlKey:
情况下Keys.Alt:
情况下Keys.Shift:
情况下Keys.ShiftKey:
/ /允许控制,ALT和放大器;换挡
中断;
情况下Keys.Left:
情况下Keys.Right:
情况下Keys.Up:
情况下Keys.Down:
情况下Keys.PageUp:
案Keys.PageDown:
情况下Keys.Home:
情况下Keys.End:
//允许导航键
中断;
情况下Keys.Back:
情况下Keys.Delete:
//允许退格和放大器;删除
中断;
默认:
//压制任何其他键
e.SuppressKeyPress = TRUE;
e.Handled = TRUE;
Interaction.Beep();
中断;
}
}







,然后,因为用户可能值粘贴到文本框中,添加以下到TextBox的验证事件

 私人无效TextBox1_Validating(对象发件人,
System.ComponentModel.CancelEventArgs E)
{
//以防万一的值粘贴,
//我们需要验证值
如果(Information.IsNumeric(((文本框)发送方)。文本)!)
{
e.Cancel = TRUE;
}
}






我写了一个类来处理各种过滤器为你[这显然包含了特定的文化小数点符号。



这个类添加到您的项目

 使用Microsoft.VisualBasic程序; 
使用系统; System.Collections中使用
;
使用System.Collections.Generic;
使用System.Data这;使用System.Diagnostics程序
;
公共类TextBoxFilter
{
[旗()]
公共枚举过滤器
{
无= 0,
文本= 1,
号= 2,
字母= Filters.Text | Filters.Numbers,
货币= 4,
=所有Filters.Text | Filters.Numbers | Filters.Currency
}

&字典LT;文本框,过滤器和GT; _keyFilter;
&字典LT;文本框,串> _allowedKeys;
&字典LT;文本框,串> _invalidKeys;

&字典LT;文本框,Windows.Forms.KeyEventArgs> keyEventArgs;
私人静态字符串DecimalMark = Application.CurrentCulture.NumberFormat.NumberDecimalSeparator;
私人静态字符串NegativeMark = Application.CurrentCulture.NumberFormat.NegativeSign;
私人静态字符串CurrencySymb = Application.CurrentCulture.NumberFormat.CurrencySymbol;

私人静态字符串CurrencyDecimal = Application.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;

公共TextBoxFilter()
{
_keyFilter =新词典<文本框,过滤器和GT;();
_allowedKeys =新词典<文本框,串>();
_invalidKeys =新词典<文本框,串>();
keyEventArgs =新词典<文本框,KeyEventArgs>();
}

//设置和放大器;去除过滤器

公共无效SetTextBoxFilter(文本框文本框中滤器)
{
SetTextBoxFilter(文本框中过滤器,AllowedKeys(的textBox),InvalidKeys(textBox中));
}

公共无效SetTextBoxFilter(文本框文本框中字符串allowedKeys)
{
SetTextBoxFilter(文本框中Strings.Filter(的textBox),allowedKeys,InvalidKeys(textBox中)) ;
}


公共无效SetTextBoxFilter(文本框文本框中字符串allowedKeys,串invalidKeys)
{
SetTextBoxFilter(文本框中Strings.Filter(的textBox) allowedKeys,invalidKeys);
}


公共无效SetTextBoxFilter(文本框文本框中滤器,串allowedKeys,串invalidKeys)
{
如果(!_keyFilter.ContainsKey(textBox中)){$ b $B∥加上文本框和其过滤,如果它不为注册文本框$ b $的集合体b _keyFilter.Add(文本框中滤波器)在
//存在;
_allowedKeys.Add(文本框中allowedKeys);
_invalidKeys.Add(文本框中invalidKeys);
keyEventArgs.Add(文本框中新System.Windows.Forms.KeyEventArgs(Keys.None));

//添加事件处理程序
textBox.KeyDown + = KeyDownUp;
textBox.KeyUp + = KeyDownUp;
textBox.KeyPress + =的KeyPress;
textBox.Validating + =验证;
textBox.Disposed + =处置;如果在
存在注册文本框
_keyFilter(textBox中)=滤波器//收集

}其他{
//改变文本框的过滤器;
_allowedKeys(textBox中)= allowedKeys;
_invalidKeys(textBox中)= invalidKeys;
}
}

公共无效RemoveTextBoxFilter(文本框的textBox)
{
如果(_keyFilter.ContainsKey(textBox中)){
_keyFilter。删除(的textBox);
_allowedKeys.Remove(的textBox);
_invalidKeys.Remove(的textBox);
keyEventArgs.Remove(的textBox);

textBox.KeyDown - = KeyDownUp;
textBox.KeyUp - = KeyDownUp;
textBox.KeyPress - =的KeyPress;
textBox.Validating - =验证;
textBox.Disposed - =处置;
}
}

公共BOOL ContainsTextBox(文本框的textBox)
{
返回_keyFilter.ContainsKey(的textBox);
}

//性质

公共过滤器过滤{
获得{
如果(ContainsTextBox(textBox中)){
返回_keyFilter.Item [textBox中];
}其他{
返回Filters.None;
}
}
集合{SetTextBoxFilter(文本框中的值); }
}

公共字符串AllowedKeys {
获得{
如果(ContainsTextBox(textBox中)){
返回_allowedKeys(的textBox);
}其他{
返回;
}
}
集合{SetTextBoxFilter(文本框中this.Filter(的textBox),价值,this.InvalidKeys(textBox中)); }
}

公共字符串InvalidKeys {
获得{
如果(ContainsTextBox(textBox中)){
返回_invalidKeys(的textBox);
}其他{
返回;
}
}
集合{SetTextBoxFilter(文本框中this.Filter(的textBox),this.AllowedKeys(的textBox),价值); }
}

//事件处理

私人无效处理完毕(对象发件人,发送System.EventArgs)
{
RemoveTextBoxFilter((文本框)发送者);
}

私人无效KeyDownUp(对象发件人,System.Windows.Forms.KeyEventArgs E)
{
//指定修饰符
keyEventArgs((文本框)发件人)= E;
}

私人无效的KeyPress(对象发件人,System.Windows.Forms.KeyPressEventArgs E)
{
//确保按键是在允许键

对象的txt =(文本框)发送;
对象C = e.KeyChar;
布尔allowKey = IsValidChar(TXT,C,txt.SelectionStart);


//检查退格键和放大器; Ctrl键的组合,如果allowKey还是假的
如果(allowKey == FALSE){
如果(keyEventArgs(TXT)。控制){
//控制修饰符去与A,X,C, V和Z表示
//全选,剪切,复制,粘贴和撤销分别为
对象键= keyEventArgs(TXT).KeyCode;
allowKey =(键== || Keys.A关键== || Keys.X关键== || Keys.C关键== || Keys.V关键== Keys.Z);

}否则如果(keyEventArgs(TXT).KeyCode == Keys.Back){
//允许退格键
allowKey = TRUE;
}
}


//禁用的关键,如果它是不是有效的
如果(!allowKey){
e.Handled =真正;
Interaction.Beep();
}
}

私人无效验证(对象发件人,System.ComponentModel.CancelEventArgs E)
{
对象盒=(文本框)发送;
对象boxFlags = _keyFilter(盒);

//跳过验证如果文本框允许所有条目,或没有文字
如果(boxFlags == Filters.All | string.IsNullOrEmpty(box.Text))
返回;

//否则检查输入的字符
对象txtChars = box.Text.ToCharArray;

布尔isValidEntry = FALSE;

//检查每个卡拉科特一个无效的条目
为(i = 0; I< = txtChars.Length - 1;我++){$​​ B $ B对象C = txtChars(我);
isValidEntry = IsValidChar(箱,txtChars(我),我);

如果(isValidEntry!){
box.Select(I,1);
中断; // TODO:可能不正确。是:(!isValidEntry)退出对于
}
}

如果
e.Cancel = TRUE;

如果(!isValidEntry){
Interaction.MsgBox(输入的文本的格式无效+ boxFlags.ToString +。+!string.IsNullOrEmpty(_allowedKeys(盒) )Constants.vbCrLf +附加允许的按键:+ _allowedKeys(箱):+ string.IsNullOrEmpty(_invalidKeys(盒!))Constants.vbCrLf +?其他的无效键:+ _invalidKeys(盒): ,MsgBoxStyle.Critical,无效条目);
}
}

私人布尔IsValidChar(文本框文本框中焦炭C中,int charIndex处)
{
//确保按键是在允许的钥匙

对象PF = _keyFilter(的textBox);
对象AK = _allowedKeys(的textBox);
对象IK = _invalidKeys(的textBox);
布尔shouldAllow = FALSE;


//如果过滤器设置为所有,返回true无条件
如果(PF == Filters.All)
返回真;


//检查预设的过滤器

//检查文本
如果(EnumHasFlag(PF,Filters.Text)){
如果{
shouldAllow =真(char.IsDigit(C)!);
}其他{
//如果字符是一个数字,检查数量标志(字母数字)
如果(EnumHasFlag(PF,Filters.Numbers)){
shouldAllow =真正;
}
}

}

//检查量拟合选取
如果(shouldAllow ==假放;&安培; EnumHasFlag(PF, Filters.Numbers)){
如果(char.IsDigit(C)){
shouldAllow = TRUE;
}否则如果(DecimalMark.Contains(c))的{
//允许小数如果在文本框中的
//文本或所选文本没有小数包含该标记
如果{
shouldAllow =真(textBox.Text.Substring(0,则CHARINDEX)。载有(C)|| textBox.SelectedText.Contains(C)!);
}
}否则如果(NegativeMark.Contains(三)及及(的charIndex&下; = NegativeMark.IndexOf(C))){
//允许负标记,如果我们在
//文本框
shouldAllow开始= TRUE;
}

}

//检查币
如果(shouldAllow ==假放;&安培; EnumHasFlag(PF,Filters.Currency)) {
如果(char.IsDigit(C)){
shouldAllow = TRUE;
}否则如果(CurrencyDecimal.Contains(C)){
//允许人民币小数标志,如果它不存在于
//文本框的文本中或选中的文本包含该标记$ (!textBox.Text.Substring(0,则CHARINDEX)。载有(C)|| textBox.SelectedText.Contains(C))b $ b如果{
shouldAllow = TRUE;
}
}否则如果(CurrencySymb.Contains(C)及及(charIndex处< = CurrencySymb.IndexOf(C))){
//允许货币符号,如果我们在有效位置
shouldAllow = TRUE;
}

}



//现在检查额外允许键
如果(!shouldAllow){
shouldAllow = aK.Contains(C);
}

//,然后再检查额外的无效键
如果(shouldAllow&安培;&安培; iK.Contains(C)){
shouldAllow = FALSE;
}


返回shouldAllow;
}

[System.Diagnostics.DebuggerStepThrough()]
私人布尔EnumHasFlag(枚举值,枚举标志)
{
收益率(Convert.ToInt64 (值)及Convert.ToInt64(标志))== Convert.ToInt64(标志);
}
}



然后如下:

 公共类Form1的
{


TextBoxFilter过滤器=新TextBoxFilter();
私人无效Form1_Load的(对象发件人,发送System.EventArgs)
{
filter.SetTextBoxFilter(TextBox1中,TextBoxFilter.Filters.Numbers);
}
公共Form1中()
{
负载+ = Form1_Load的;
}
}


How can I make a textbox in which can be only typed a number like 12.00 or 1231231.00 or 123123

I've done this in a very long way and I'm looking for the best and fastest way.

Also the decimal separator must be culture specific.:

Application.CurrentCulture.NumberFormat.NumberDecimalSeparator

解决方案

That's a fairly straightforward operation. You'll need to filter the keys that you don't want out and then perform some additional checks.

Add the following code to the KeyDown event of the textbox:

private void TextBox1_KeyDown(object sender, 
  System.Windows.Forms.KeyEventArgs e)
{
    switch (e.KeyCode) {
        case Keys.D0:
        case Keys.D1:
        case Keys.D2:
        case Keys.D3:
        case Keys.D4:
        case Keys.D5:
        case Keys.D6:
        case Keys.D7:
        case Keys.D8:
        case Keys.D9:
        case Keys.NumPad0:
      case Keys.NumPad1:
        case Keys.NumPad2:
        case Keys.NumPad3:
        case Keys.NumPad4:
        case Keys.NumPad5:
        case Keys.NumPad6:
        case Keys.NumPad7:
        case Keys.NumPad8:
        case Keys.NumPad9:
            //allow numbers only when no modifiers are active
            if (e.Control || e.Alt || e.Shift) {
                //suppress numbers with modifiers
                e.SuppressKeyPress = true;
                e.Handled = true;
                Interaction.Beep();
            }
            break;
           case (Keys)110:
        case Keys.OemPeriod:
            if (!((TextBox)sender).Text.Contains(".")) {
                //allow period key if there is no '.' 
                //in the text and no modifiers are active
                if (e.Control || e.Alt || e.Shift) {
                    //suppress numbers with modifiers
                    e.SuppressKeyPress = true;
                    e.Handled = true;
                    Interaction.Beep();
                }
            } else {
                e.SuppressKeyPress = true;
                e.Handled = true;
                Interaction.Beep();
            }
            break;
        case Keys.Subtract:
        case Keys.OemMinus:
            if (((TextBox)sender).SelectionStart == 0 && 
              !((TextBox)sender).Text.Contains("-")) {
                //allow the negative key only when the cursor 
                //is at the start of the textbox
                //and there are no minuses in the textbox
                //and no modifiers are active
                if (e.Control || e.Alt || e.Shift) {
                    //suppress numbers with modifiers
                    e.SuppressKeyPress = true;
                    e.Handled = true;
                    Interaction.Beep();
                }
            } else {
                e.SuppressKeyPress = true;
                e.Handled = true;
                Interaction.Beep();
            }
            break;
        case Keys.C:
        case Keys.X:
        case Keys.V:
        case Keys.Z:
            //allow copy, cut, paste & undo by checking for 
            //the CTRL state.
            if (e.Control == false) {
                e.SuppressKeyPress = true;
                e.Handled = true;
                Interaction.Beep();
            }
            break;
        case Keys.Control:
        case Keys.ControlKey:
        case Keys.Alt:
        case Keys.Shift:
        case Keys.ShiftKey:
            //allow control, alt & shift
            break;
        case Keys.Left:
        case Keys.Right:
        case Keys.Up:
        case Keys.Down:
        case Keys.PageUp:
        case Keys.PageDown:
        case Keys.Home:
        case Keys.End:
            //allow navigation keys
            break;
        case Keys.Back:
        case Keys.Delete:
            //allow backspace & delete
            break;
        default:
            //suppress any other key
            e.SuppressKeyPress = true;
            e.Handled = true;
            Interaction.Beep();
            break;
    }
}




And then, since a user may paste values into the textbox, you add the following to the TextBox's Validate event

private void TextBox1_Validating(object sender, 
  System.ComponentModel.CancelEventArgs e)
{
    //just in case a value was pasted, 
    //we'll need to validate the value
    if (!Information.IsNumeric(((TextBox)sender).Text)) 
    {
        e.Cancel = true;
    }
}


I wrote a class to handle a variety of filters for you [which obviously includes the culture-specific decimal symbol].

Add this class to your project

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class TextBoxFilter
{
    [Flags()]
    public enum Filters
    {
        None = 0,
        Text = 1,
        Numbers = 2,
        AlphaNumeric = Filters.Text | Filters.Numbers,
        Currency = 4,
        All = Filters.Text | Filters.Numbers | Filters.Currency
    }

    Dictionary<TextBox, Filters> _keyFilter;
    Dictionary<TextBox, string> _allowedKeys;
    Dictionary<TextBox, string> _invalidKeys;

    Dictionary<TextBox, Windows.Forms.KeyEventArgs> keyEventArgs;
    private static string DecimalMark = Application.CurrentCulture.NumberFormat.NumberDecimalSeparator;
    private static string NegativeMark = Application.CurrentCulture.NumberFormat.NegativeSign;
    private static string CurrencySymb = Application.CurrentCulture.NumberFormat.CurrencySymbol;

    private static string CurrencyDecimal = Application.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;

    public TextBoxFilter()
    {
        _keyFilter = new Dictionary<TextBox, Filters>();
        _allowedKeys = new Dictionary<TextBox, string>();
        _invalidKeys = new Dictionary<TextBox, string>();
        keyEventArgs = new Dictionary<TextBox, KeyEventArgs>();
    }

//set & remove filter

    public void SetTextBoxFilter(TextBox textBox, Filters filter)
    {
        SetTextBoxFilter(textBox, filter, AllowedKeys(textBox), InvalidKeys(textBox));
    }

    public void SetTextBoxFilter(TextBox textBox, string allowedKeys)
    {
        SetTextBoxFilter(textBox, Strings.Filter(textBox), allowedKeys, InvalidKeys(textBox));
    }


    public void SetTextBoxFilter(TextBox textBox, string allowedKeys, string invalidKeys)
    {
        SetTextBoxFilter(textBox, Strings.Filter(textBox), allowedKeys, invalidKeys);
    }


    public void SetTextBoxFilter(TextBox textBox, Filters filter, string allowedKeys, string invalidKeys)
    {
        if (!_keyFilter.ContainsKey(textBox)) {
            //add the textbox and its filter if it does not exist in 
            //the collection of registered textboxes
            _keyFilter.Add(textBox, filter);
            _allowedKeys.Add(textBox, allowedKeys);
            _invalidKeys.Add(textBox, invalidKeys);
            keyEventArgs.Add(textBox, new System.Windows.Forms.KeyEventArgs(Keys.None));

            //add the event handlers
            textBox.KeyDown += KeyDownUp;
            textBox.KeyUp += KeyDownUp;
            textBox.KeyPress += KeyPress;
            textBox.Validating += Validating;
            textBox.Disposed += Disposed;

        } else {
            //change the filter of the textbox if it exists in
            //the collection of registered textboxes
            _keyFilter(textBox) = filter;
            _allowedKeys(textBox) = allowedKeys;
            _invalidKeys(textBox) = invalidKeys;
        }
    }

    public void RemoveTextBoxFilter(TextBox textBox)
    {
        if (_keyFilter.ContainsKey(textBox)) {
            _keyFilter.Remove(textBox);
            _allowedKeys.Remove(textBox);
            _invalidKeys.Remove(textBox);
            keyEventArgs.Remove(textBox);

            textBox.KeyDown -= KeyDownUp;
            textBox.KeyUp -= KeyDownUp;
            textBox.KeyPress -= KeyPress;
            textBox.Validating -= Validating;
            textBox.Disposed -= Disposed;
        }
    }

    public bool ContainsTextBox(TextBox textBox)
    {
        return _keyFilter.ContainsKey(textBox);
    }

//properties

    public Filters Filter {
        get {
            if (ContainsTextBox(textBox)) {
                return _keyFilter.Item[textBox];
            } else {
                return Filters.None;
            }
        }
        set { SetTextBoxFilter(textBox, value); }
    }

    public string AllowedKeys {
        get {
            if (ContainsTextBox(textBox)) {
                return _allowedKeys(textBox);
            } else {
                return "";
            }
        }
        set { SetTextBoxFilter(textBox, this.Filter(textBox), value, this.InvalidKeys(textBox)); }
    }

    public string InvalidKeys {
        get {
            if (ContainsTextBox(textBox)) {
                return _invalidKeys(textBox);
            } else {
                return "";
            }
        }
        set { SetTextBoxFilter(textBox, this.Filter(textBox), this.AllowedKeys(textBox), value); }
    }

//event handlers

    private void Disposed(object sender, System.EventArgs e)
    {
        RemoveTextBoxFilter((TextBox)sender);
    }

    private void KeyDownUp(object sender, System.Windows.Forms.KeyEventArgs e)
    {
        //assign the modifiers
        keyEventArgs((TextBox)sender) = e;
    }

    private void KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
        //ensure key pressed is in the allowed keys

        object txt = (TextBox)sender;
        object c = e.KeyChar;
        bool allowKey = IsValidChar(txt, c, txt.SelectionStart);


        //check for backspace & Ctrl combinations if the allowKey is still false
        if (allowKey == false) {
            if (keyEventArgs(txt).Control) {
                //control modifier goes with A, X, C, V and Z for 
                //Select All, Cut, Copy, Paste and Undo respectively
                object key = keyEventArgs(txt).KeyCode;
                allowKey = (key == Keys.A || key == Keys.X || key == Keys.C || key == Keys.V || key == Keys.Z);

            } else if (keyEventArgs(txt).KeyCode == Keys.Back) {
                //allow the backspace key
                allowKey = true;
            }
        }


        //disable the key if it was not valid
        if (!allowKey) {
            e.Handled = true;
            Interaction.Beep();
        }
    }

    private void Validating(object sender, System.ComponentModel.CancelEventArgs e)
    {
        object box = (TextBox)sender;
        object boxFlags = _keyFilter(box);

        //skip validation if the textbox allows all entries or there is no text
        if (boxFlags == Filters.All | string.IsNullOrEmpty(box.Text))
            return;

        //otherwise check the characters entered
        object txtChars = box.Text.ToCharArray;

        bool isValidEntry = false;

        //check each caracter for an invalid entry
        for (i = 0; i <= txtChars.Length - 1; i++) {
            object c = txtChars(i);
            isValidEntry = IsValidChar(box, txtChars(i), i);

            if (!isValidEntry) {
                box.Select(i, 1);
                break; // TODO: might not be correct. Was : Exit For
            }
        }

        if (!isValidEntry)
            e.Cancel = true;

        if (!isValidEntry) {
            Interaction.MsgBox("The text entered is invalid for the format " + boxFlags.ToString + "." + !string.IsNullOrEmpty(_allowedKeys(box)) ? Constants.vbCrLf + "Additional Allowed Keys: " + _allowedKeys(box) : "" + !string.IsNullOrEmpty(_invalidKeys(box)) ? Constants.vbCrLf + "Additional Invalid Keys: " + _invalidKeys(box) : "", MsgBoxStyle.Critical, "Invalid Entry");
        }
    }

    private bool IsValidChar(TextBox textBox, char c, int charIndex)
    {
        //ensure key pressed is in the allowed keys

        object pF = _keyFilter(textBox);
        object aK = _allowedKeys(textBox);
        object iK = _invalidKeys(textBox);
        bool shouldAllow = false;


        //if filter is set to all, return true unconditionally
        if (pF == Filters.All)
            return true;


        //check preset filters

        //check for text
        if (EnumHasFlag(pF, Filters.Text)) {
            if (!char.IsDigit(c)) {
                shouldAllow = true;
            } else {
                //if the character is a digit, check for the number flag (AlphaNumerics)
                if (EnumHasFlag(pF, Filters.Numbers)) {
                    shouldAllow = true;
                }
            }

        }

        //check for nubers
        if (shouldAllow == false && EnumHasFlag(pF, Filters.Numbers)) {
            if (char.IsDigit(c)) {
                shouldAllow = true;
            } else if (DecimalMark.Contains(c)) {
                //allow the decimal if there is no decimal in the textbox's
                //text or the selected text contains the mark
                if (!textBox.Text.Substring(0, charIndex).Contains(c) || textBox.SelectedText.Contains(c)) {
                    shouldAllow = true;
                }
            } else if (NegativeMark.Contains(c) && (charIndex <= NegativeMark.IndexOf(c))) {
                //allow the negative mark if we are at the start of the
                //textbox
                shouldAllow = true;
            }

        }

        //check for currency
        if (shouldAllow == false && EnumHasFlag(pF, Filters.Currency)) {
            if (char.IsDigit(c)) {
                shouldAllow = true;
            } else if (CurrencyDecimal.Contains(c)) {
                //allow the currency decimal mark if it does not exist in the
                //textbox's text or the selected text contains the mark
                if (!textBox.Text.Substring(0, charIndex).Contains(c) || textBox.SelectedText.Contains(c)) {
                    shouldAllow = true;
                }
            } else if (CurrencySymb.Contains(c) && (charIndex <= CurrencySymb.IndexOf(c))) {
                //allow the currency symbol if we are in a valid position
                shouldAllow = true;
            }

        }



        //now check for extra allowed keys
        if (!shouldAllow) {
            shouldAllow = aK.Contains(c);
        }

        //and then check for extra invalid keys
        if (shouldAllow && iK.Contains(c)) {
            shouldAllow = false;
        }


        return shouldAllow;
    }

    [System.Diagnostics.DebuggerStepThrough()]
    private bool EnumHasFlag(Enum value, Enum flag)
    {
        return (Convert.ToInt64(value) & Convert.ToInt64(flag)) == Convert.ToInt64(flag);
    }
}

and then use it in your form as follows

public class Form1
{


    TextBoxFilter filter = new TextBoxFilter();
    private void Form1_Load(object sender, System.EventArgs e)
    {
        filter.SetTextBoxFilter(TextBox1, TextBoxFilter.Filters.Numbers);
    }
    public Form1()
    {
        Load += Form1_Load;
    }
}

这篇关于限制在C#中的文本框输入小数的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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