开发者

Allow user to only input text?

how do I make a boolean statement to only allow text开发者_JAVA技巧? I have this code for only allowing the user to input numbers but ca'nt figure out how to do text.

 bool Dest = double.TryParse(this.xTripDestinationTextBox.Text, out Miles);
 bool MilesGal = double.TryParse(this.xTripMpgTextBox.Text, out Mpg);
 bool PriceGal = double.TryParse(this.xTripPricepgTextBox.Text, out Price);


Update: looking at your comment I would advise you to read this article:

User Input Validation in Windows Forms


Original answer: The simplest way, at least if you are using .NET 3.5, is to use LINQ:

bool isAllLetters = s.All(c => char.IsLetter(c));

In older .NET versions you can create a method to do this for you:

bool isAllLetters(string s)
{
    foreach (char c in s)
    {
        if (!char.IsLetter(c))
        {
            return false;
        }
    }
    return true;
}

You can also use a regular expression. If you want to allow any letter as defined in Unicode then you can use this regular expression:

bool isOnlyLetters = Regex.IsMatch(s, @"^\p{L}+$");

If you want to restrict to A-Z then you can use this:

bool isOnlyLetters = Regex.IsMatch(s, @"^[a-zA-Z]+$");


You can use following code in the KeyPress event:

if (!char.IsLetter(e.KeyChar)) {
e.Handled = true;
}


You can use regular expression, browse here: http://regexlib.com/


You can do one of a few things.

  1. User Regular Expression to check that the string matches your concept of 'Text' only
  2. Write some code that checks each character against a list of valid characters. Or even use char.IsLetter()
  3. Use the MaskedTextBox and set a custom mask to limit input to text only characters


I found hooking up into the text changed event of a textbox and accepting/rejecting the changes an acceptable solution. To "only allow text" is a rather vague definition, but you may as well check if your newly added text (the next char) is a number or not and simply reject all numbers/disallowed characters. This will make users feel they can only enter characters and special characters (like dots, question marks etc.).

private void UTextBox_TextChanged(object sender, EventArgs e)
{
    string lastCharacter = this.Text[this.Text.Length-1].ToString();
    MatchCollection matches = Regex.Matches(lastCharacter, "[0-9]", RegexOptions.None);
    if (matches.Count > 0) //character is a number, reject it.
    {
         this.Text = Text.Substring(0, Text.Length-1);
    }
 }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜