[英]C# Windows Form FormatException was unhandled
我試圖在文本框中輸入不大於100的值,但是我在使用formatExeception可以在這方面提供任何幫助。
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (Int32.Parse(textBox1.Text) > 100)
{
MessageBox.Show("No. Of Elements Must be Less Then 100");
}
}
如果文本框的內容無法解析為Int32,則需要用try-catch包圍語句。 假設您遇到了異常,則可以獲取一條描述錯誤原因的消息。
如果只希望用戶輸入數字,但由於無法將文本框中的文本解析為數字而發生錯誤,則最好使用數字上移。 使用int.TryParse。 如果無法將字符串解析為數字,則不會拋出異常
int numElements = 0;
int.TryParse(textBox1.Text, out numElements);
if(numElements >100){
MessageBox.Show("No. Of Elements Must be Less Then 100");
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
int parsed = 0;
if (!int.TryParse(textBox1.Text), out parsed)
{
MessageBox.Show("No. You must enter a number!");
return;
}
if (parsed > 100)
{
MessageBox.Show("No. Of Elements Must be Less Then 100");
}
}
解析引發解析錯誤時拋出異常的屬性頗為煩人 。 正是這樣,框架開發人員在2.0版本中添加了TryParse。 如果要解析字符串,則在經過初始開發階段后就應該始終使用TryParse。
或理想情況下,是一種驗證/輸入的方法,不允許有錯誤的輸入(如Ken Tucker指出的數字上/下)。
如果您因某種原因無法訪問TryParse,則可以回寫它的副本:
//Parse throws ArgumentNull, Format and Overflow Exceptions.
//And they only have Exception as base class in common, but identical handling code (output = 0 and return false).
bool TryParse(string input, out int output){
try{
output = int.Parse(input);
}
catch (Exception ex){
if(ex is ArgumentNullException ||
ex is FormatException ||
ex is OverflowException){
//these are the exceptions I am looking for. I will do my thing.
output = 0;
return false;
}
else{
//Not the exceptions I expect. Best to just let them go on their way.
throw;
}
}
//I am pretty sure the Exception replaces the return value in exception case.
//So this one will only be returned without any Exceptions, expected or unexpected
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.