2016-11-18 48 views
0

我在C#中构建Windows窗体,并试图测试用户输入是否在1和7之间(表示天数在一周内,电影可以出租)。如果测试返回false,那么我想输出一条错误消息。我正在使用文本框来获取用户输入。问题是,我一直在运行程序时收到此错误:如何在C#中使用TextBox时测试Integer是否在范围内

System.FormatException了未处理

的HResult = -2146233033

消息=输入字符串的不正确的格式。

有人可以请告诉我我做错了什么。 预先感谢您。

这是我写的代码..

private void nightsRentedTextBox_TextChanged_1(object sender, EventArgs e) 
    { 
     Boolean inputBoolean = true; 

     if (int.Parse(nightsRentedTextBox.Text) < 1) 
     { 
      MessageBox.Show("Enter a number between 1 and 7", "INPUT ERROR", 
      MessageBoxButtons.OK, MessageBoxIcon.Error); 
      inputBoolean = false; 
     } 
+1

开始与使用的TryParse()..... –

回答

1

您应该使用TryParse代替。

int nightsRented; 
bool res = int.TryParse(nightsRentedTextBox.Text, out nightsRented); 
if (res == false) 
{ 
    // String is not a number. 
} 

,或者您可以使用它像

int nightsRented; 
if (int.TryParse(nightsRentedTextBox.Text, out nightsRented);) 
{ 
    if (nightsRented >= 1 || nightsRented <= 7) 
    { 
     MessageBox.Show("Enter a number between 1 and 7", "INPUT ERROR", 
     MessageBoxButtons.OK, MessageBoxIcon.Error); 
     inputBoolean = false; 
    } 
} 
+0

可以使用,如果(Enumerable.Range(1,7)。载有(NumberOfNights))太。 – Yanga

+0

Mohit,你的答案完美无缺! –

+0

乐于助人。 :) @CaseySmith –

相关问题