0

I'm having a little problem! I want to restrict the users of my programm from using anything but letters in certain textboxes, which currently looks like this

private void textBox_Ansprechpartner_Name_TextChanged(object sender, EventArgs e)
{
    if (!System.Text.RegularExpressions.Regex.IsMatch(textBox_Ansprechpartner_Name.Text, "^[a-zA-Z ]"))
    {
        MessageBox.Show("This textbox may only contain letters.");
        textBox_Ansprechpartner_Name.Text = string.Empty;
    }            
}

Which works just fine, until you actually want to use backspace for example, which makes it empty the textbox again with the same message. Another problem I have is, that it shows the message box when it detects that the input is disallowed aswell as when emptying the field itself.

I tried allowing backspaces by adding \b but the only thing that does is disallowing letters all together.

I'm in a bit of a weird situataion as nothing I've tried so far has worked out.

Help would be greatly appreciated

1 Answers1

0

Try this:

string s = textBox_Ansprechpartner_Name.Text;
//shouldn't be necessary    
//if (string.IsNullOrEmpty(s)) return;
foreach (var c in s)
    if (!char.IsLetter(c))
    {
        textBox_Ansprechpartner_Name.Text = "":
        MessageBox.Show("This textbox may only contain letters.");
        return;
    }
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69