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;
}
nxbita
  • 1
  • 1
  • 1
    What do you mean "it affected the other codes."? Also, how is this related to sql? – HoneyBadger Nov 11 '21 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). – Auditive Nov 11 '21 at 15:02
  • Try this to remove digits: https://stackoverflow.com/questions/1657282/how-to-remove-numbers-from-string-using-regex-replace – mggSoft Nov 11 '21 at 15:04

1 Answers1

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:

Auditive
  • 1,607
  • 1
  • 7
  • 13