TextBox validation in Windows Forms
I have some code that is meant to check a TextBox for certain characters, alt开发者_StackOverflow中文版hough for some reason I am having problems with "KeyChar" and "Handled" part of the code:
private void textBox5_Validating(object sender, CancelEventArgs e)
{
string allowedCharacterSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.\b\n";
if (allowedCharacterSet.Contains(e.KeyChar.ToString()))
{
if (e.KeyChar.ToString() == "."
&& textBox5.Text.Contains("."))
{
e.Handled = true;
}
}
else
{
e.Handled = true;
}
}
.............
Error 2 'System.ComponentModel.CancelEventArgs' does not contain a definition for 'KeyChar' and no extension method 'KeyChar' accepting a first argument of type 'System.ComponentModel.CancelEventArgs' could be found (are you missing a using directive or an assembly reference?) D:\test\Form1.cs 602 48 App
As the error says, there is no KeyChar
property in CancelEventArgs
.
Either you have to switch to KeyPress
Event (which has KeyChar
property in it's event args) of the textbox or consider the string as a whole (rather than one char at a time) in Validating
Event
How about using regular expressions instead?
private void TextBox5_Validating(object sender, System.EventArgs e)
{
String AllowedChars = @"^a-zA-Z0-9.$";
if(Regex.IsMatch(TextBox5.Text, AllowedChars))
{
e.Handled = true;
}
else
{
e.Handled = false;
}
}
Or something along these lines....
Try using KeyPressEventArgs e
instead of CancelEventArgs e
http://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.aspx
Try the KeyPress
event instead. This lets you prevent users from typing in a letter that you don't want (by setting e.Handled = true
). You'll still want to use Validating to make sure that they didn't paste some bad data from the clipboard.
精彩评论