maskedtextbox文本被拒绝

时间:2013-01-19 02:03:37

标签: c# winforms maskedtextbox

我正在试图弄清楚如何制作它,以便如果我按下我的按钮进行动作,(比如显示一个消息框)和我的maskedtextbox的文本不是一个数字,那么它去做并做了类似的事情你只能在TextBox中有一个数字或类似的东西。我似乎无法弄明白。

我试过用这个:

if (!System.Text.RegularExpressions.Regex.IsMatch(binTxtbx.Text, @"0-9"))
            e.Handled = true;

但如果我使用它,它就不会将任何文本放入maskedtextbox。

如果你知道是否有人问我做过同样的问题,请告诉我。

3 个答案:

答案 0 :(得分:3)

如果你不介意使用maskedTextBox,而只是不喜欢下划线(正如你在评论中提到的那样),只需将PromptChar更改为空白即可。

您可以在MaskedTextBox属性的设计视图中执行此操作,也可以在以下代码中执行此操作:

myMaskedTextBox.PromptChar = ' ';

<小时/> 编辑:

或者,(如果你不想使用maskedTextBox)你可以将KeyDown事件连接到这样的EventHandler:

    private void numericComboBox_KeyDown(object sender, KeyEventArgs e)
    {
        try
        {
            e.SuppressKeyPress = false;

            // Determine whether the keystroke is a number from the top of the keyboard.
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                // Determine whether the keystroke is a number from the keypad.
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    // Determine whether the keystroke is a backspace or arrow key
                    if ((e.KeyCode != Keys.Back) && (e.KeyCode != Keys.Up) && (e.KeyCode != Keys.Right) && (e.KeyCode != Keys.Down) && (e.KeyCode != Keys.Left))
                    {
                        // A non-numerical keystroke was pressed.
                        // Set the flag to true and evaluate in KeyPress event.
                        e.SuppressKeyPress = true;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            //Handle any exception here...
        }
    }

答案 1 :(得分:1)

表达式应为[0-9],带方括号。

完整代码:

!System.Text.RegularExpressions.Regex.IsMatch(binTxtbx.Text, "^[0-9]*$")

答案 2 :(得分:1)

也许你可以使用

if (binTxtbx.Text.Any(c => char.IsNumber(c)))
{
   // found a number in the string
}

if (binTxtbx.Text.All(c => char.IsNumber(c)))
{
    // the string is a number
}