"titan nyquist" wrote:
How do you test a string to see if it contains special characters?
Iwant to ensure that any names typed into my form has only letters
(and maybe allow a dash and an apostrophe).
I can loop RealName.Contains("..."), but there must be a more
elegant solution.
Another possible approach:
Create a Custom User Control TextBox and override OnKeyPress to
handle ASCII characters.
protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
{
// KeyChar property of the event Gets or Sets the
// character corresponding to the key pressed
// and returns the ASCII character that is composed.
// Handled property of the event Gets or Sets a value
// indicating whether the System.Windows.Forms.Control
// .KeyPress event was handled
// and returns true if the event is handled; otherwise,
// false
int i = (int)e.KeyChar; //cast KeyChar property to integer
// Capital letters, small case letters, dash (or minus),
// and apostrophe keys are not handled (handled returns
// false) so are passed to the textBox and displayed.
// All other KeyPresses are handled (handled returns true)
// so are not passed to the textBox and are not displayed.
if (i >= 65 && i <= 90 || i >= 96 && i <= 122 || i == 39)
{
e.Handled = false;
return;
}
e.Handled = true;
}
-Tim Sprout