2011-03-25 93 views

回答

10

要麼使用Int32.ParseInt32.TryParse,或者您可以使用System.Convert.ToInt32

int intValue = 0; 
if(!Int32.TryParse(yourTextBox.Text, out intValue)) 
{ 
    // handle the situation when the value in the text box couldn't be converted to int 
} 

解析和的TryParse之間的差異是很明顯的。如果後者無法將字符串解析爲整數,那麼後者會優雅地失敗,而另一方會拋出異常。但是Int32.Parse和System.Convert.ToInt32之間的差異更加微妙,通常與文化特定的解析問題有關。基本上如何解釋負數和小數以及數千分隔符。

1

您可以使用Int32.Parse(myTextBox.text)

2
int temp; 

if (int.TryParse(TextBox1.Text, out temp)) 
    // Good to go 
else 
    // display an error 
1

如果是這樣的WinForms,你可以使用一個NumericUpDown控件。如果這是webforms,我會使用Int32.TryParse方法以及輸入框上的客戶端數字過濾器。

1
int orderID = 0; 

orderID = Int32.Parse(txtOrderID.Text);