首页 > 解决方案 > 检查文本框是否包含数字和字符串

问题描述

我是一名新程序员,我有一个项目,我希望文本框包含字母和至少 1 个数字。这是我的代码:

private void button1_Click(object sender, EventArgs e)
        {
            StreamWriter sw = File.AppendText("name.txt");

            if (String.IsNullOrEmpty(textBox1.Text)) 
            {
                MessageBox.Show("Invalid name!\nPlease Try Again!");
            }
            else if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]*$") && System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[0-9]"))
            {
                MessageBox.Show("The field accepts only letters and at least one number!\nPlease Try Again");
            }
            else
            {
                sw.WriteLine(textBox1.Text);
                MessageBox.Show("Player added Successfully!");
                Form3 f3 = new Form3();
                f3.Show();
            }
            sw.Close();
        }

标签: c#textboxnumbersintegerc-strings

解决方案


要检查您的字符串是否仅包含数字和字母,您可以Char.IsLetterOrDigit()结合使用String.All()来检查该字符串中的所有字符是否与给定类型匹配。

此外,我还使用Char.IsDigit()了 withString.Any()来检查至少一个字符是否是数字。

例子:

string s = textBox1.Text;

// Check if all of the letters are only Letters and Digits
// and if atleast one is a Digit.
bool result = !s.All(Char.IsLetterOrDigit) || !s.Any(Char.IsDigit);

我还添加IsNullOrWhiteSpace了一个检查用户是否输入了文本,但它只包含空格。此外,我将代码封装在 using 块中,以便它在离开 using 块后Streamwriter自动调用该方法。Dispose()

代码中的示例:

using (StreamWriter sw = File.AppendText("name.txt")) {
    string s = textBox1.Text;
    // Check if string consits of only whitespaces, nothign or if it is null.
    if (String.IsNullOrWhiteSpace(s)) {
        MessageBox.Show("Invalid name!\nPlease Try Again!");
    }
    // Check if all of the letters are only Letters and Digits
    // and if atleast one is a Digit.
    else if (!s.All(Char.IsLetterOrDigit) || !s.Any(Char.IsDigit)) {
        MessageBox.Show("The field accepts only letters and 
            + at least one number!\nPlease Try Again");
    }
    else {
        sw.WriteLine(s);
        MessageBox.Show("Player added Successfully!");
        Form3 f3 = new Form3();
        f3.Show();
    }
}

推荐阅读