c#验证以确保输入数字

时间:2014-05-22 18:54:10

标签: c#

我想确保用户输入1到100之间的数字。如果他们没有或输入一个字母,我需要显示一条错误消息

    private void button1_Click(object sender, EventArgs e)
    {           
        guesses++;
        label4.Text = guesses.ToString();

        int guess = Convert.ToInt32(textBox1.Text);


        if (guess > number)
        {

            MessageBox.Show("The value is lower than" + guess);

        }

        if (guess < number)
        {
            MessageBox.Show("The Value is bigger than" + guess);

        }
        if (guess == number)
        {
            MessageBox.Show("Well done!! The number was" + guess);
        }


    }

2 个答案:

答案 0 :(得分:1)

使用Int32.TryParse(返回布尔值)而不是Convert.ToInt32(如果转换失败,将引发异常。

int guess;

if (!Int32.TryParse(textBox1.Text, out guess)) {
 //error message;
}

答案 1 :(得分:1)

int guess;
bool numberEntered = int.TryParse(textBox1.Text, out guess);

if (!numberEntered)
    MessageBox.Show("Invalid characters detected!");
else if (guess > 100)
    MessageBox.Show("Number too big!");
else if (guess < 1)
    MessageBox.Show("Number too small!");

如果TryParse无法从字符串中删除数字,则会返回false。