0

So I am trying to put an error message for a textbox. The error message will show that only numbers are allowed after pressing a submit button. Are there any codes like that which will not affect the rest of my codes? I tried using the codes below but the error message does not show so an error occured.

if (System.Text.RegularExpressions.Regex.IsMatch(textbox1.Text, @"[^0-9],[^0-9]"))
{
  MessageBox.Show("Only Numbers Allowed.");
  textbox1.Text = textbox1.Text.Remove(textbox1.Text.Length - 1);
  return;
}
3
  • 1
    What do you mean "it affected the other codes."? Also, how is this related to sql? Commented Nov 11, 2021 at 14:56
  • Which type of program you use? You can put this kind of code on KeyPress handler (if Windows Forms) or PreviewKeyDown handler (if WPF). Commented Nov 11, 2021 at 15:02
  • Try this to remove digits: stackoverflow.com/questions/1657282/… Commented Nov 11, 2021 at 15:04

1 Answer 1

0

If you want allow only digits be inputed to TextBox, it's better to use key press/key down handlers to capture what key was pressed and handle it, if key isn't digit:

For Windows Forms:

public Form1()
{
    InitializeComponent();
    textBox1.KeyPress += OnKeyPress;
}

private void OnKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0-9]"))
        e.Handled = true;

    // or shorter

    if (!char.IsDigit(e.KeyChar))
        e.Handled = true;
}

For WPF:

public MainWindow()
{
    InitializeComponent();
    textBox1.PreviewKeyDown += OnKeyDown;
}

private void OnKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (!System.Text.RegularExpressions.Regex.IsMatch(e.Key.ToString(), "[0-9]"))
        e.Handled = true;
}

Don't forget, that instead of input from keyboard, text may be pasted to TextBox, so you may need some OnPaste handlers, examples of which you can find:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.