Search code examples
c#winformsmaskedtextbox

maskedtextbox text rejected


I am trying to figure out how to make it so that if I press my button to do a action, (like show a messagebox) and my maskedtextbox's text isn't a number, then it goes and does something like say that you can only have a number in the TextBox or something like that. I can't seem to figure it out.

I have tried to use this:

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

But if I use that it wont put any text into the maskedtextbox.

If you know if anyone asked the same question that I did, please tell me.


Solution

  • If you don't mind using a maskedTextBox, and just don't like the underscores (as you mentioned in your comment), simply change the PromptChar to a blank.

    You can do this either in the Design View in the MaskedTextBox Properties, or in the code like this:

    myMaskedTextBox.PromptChar = ' ';
    


    EDIT:

    Alternatively, (if you don't want to use a maskedTextBox) you could wire the KeyDown event to an EventHandler like this:

        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...
            }
        }