开发者

Using TryParseExact with WindowsForms Textbox

I am currently trying to validate a textbox, so only letters (a-Z) can be entered, with the use of TryParseExact.

I have a code to check a time, although could someone demonstrate how this could be done with letters only.

My code is as follows:

private void textBox2_Validating(object sender, CancelEventArgs e)
{
    DateTime dateEntered;

    if (DateTime.TryParseExact(textBox2.Text, "HH:mm", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateEntered))
    {

    }
    else
    {
        MessageBox.Show("You need to en开发者_Go百科ter valid 24 hour time");
    }
}


This checks if all characters in a string s are a letter:

bool result = s.All(ch => char.IsLetter(ch));

See also: Char.IsLetter Method (MSDN)

If you want to accept only ASCII letters (i.e. a-z and A-Z):

bool result = s.All(ch => (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'));


You should not use any try-parse method because checking if a string only contains a-Z chars is not the same as parsing a date or a number.

I think you can use regular expressions to validate the input.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜