C#如何检查文本框是否包含数字?

问题描述:

例如我有文本框名称,当然我不能在其中写入数字,因为名称不能是数字,我该怎么检查呢?



我的尝试:



for example i have textbox Name, and of course i can't write in it a number, because the name can't be number,how can i check it?

What I have tried:

string alph = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
            if (!textBox1.Text.Contains(alph))
            {
                
                MessageBox.Show("This field only for letters", "Name");
                
            }

首先,名字可以包含任何内容:John Henderson-Allan是有效的名称。 StopFortnumAndMasonFoieGras Cruelty.com和Brfxxccxxmnpcccclllmmnprxvclmnckssqlbb11116也是如此 - 所以你不应该特别禁止任何名称,不应该禁止任何这些!#
First off, names can contain anything: "John Henderson-Allan" is a valid name. So are "StopFortnumAndMasonFoieGras Cruelty.com" and "Brfxxccxxmnpcccclllmmnprxvclmnckssqlbb11116" - so you shouldn't ban anything in particular from a name, any more than you should ban any of these "!#


% &'* + - / =?^ _`{|}〜来自电子邮件地址。



但是,要将文本框限制为大写和小写字母只使用正则表达式:

%&'*+-/=?^_`{|}~" from an email address.

But, to restrict a textbox to upper and lower case letters only just use a Regex:
Regex regex = new Regex("^[a-zA-Z]+


);
bool hasOnlyAlpha = regex.IsMatch(myTextBox.Text);
"); bool hasOnlyAlpha = regex.IsMatch(myTextBox.Text);