2012-12-01 105 views
0

爲什麼我會收到錯誤Input string was not in a correct format。在我的代碼的這一行? 輸入字符串格式不正確

Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) 

下面是完整的代碼我使用它:

foreach (ListViewItem iiii in listView1.Items) 
{ 
    if (Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) <= Convert.ToInt32(tenthousand.ToString())) 
    { 
     message2 = "GREAT"; 
     msgColor2 = System.Drawing.Color.Green; 
     break; // no need to check any more items - we have a match! 
    } 

    labelVideoViews2.Text = message2; 
    labelVideoViews2.ForeColor = msgColor2; 
} 

回答

0

Convert.ToInt32方法時傳遞到它的刺是不是數字將拋出此異常。

如果該值不包含可選符號,後跟數字序列(0到9),則會拋出此異常。所以請確保字符串值listView1.Items[4].SubItems[4].ToString()是一個有效的數字,並且只包含0-9的數字和開頭的可選符號。

另外,您可以使用int.TryParse方法,該方法不會拋出異常:

int result; 
if (int.tryParse(listView1.Items[4].SubItems[4].ToString(), out result)) 
{ 
    // the value was successfully parsed to an integer => use the result variable here 
} 
else 
{ 
    // the supplied value was not a valid number 
} 
0

最有可能你的字符串包含int像字母,甚至以外的字符點陣

前做轉換調試您的應用程序並確保實際上只有號碼

listView1.Items[4].SubItems[4].ToString() 
0

我不認爲你需要convert convert串並分析它回:

Convert.ToInt32(tenthousand.ToString()) 

而且你列舉了所有項目,但只使用一個來回listView1.Items[4]。我認爲這是錯誤的。並使用Int32.TryParse來避免解析異常:

foreach (ListViewItem iiii in listView1.Items) 
{ 
    int value; 
    string text = iiii.SubItems[4].ToString(); 
    if (!Int32.TryParse(text, out value)) 
    { 
     MessageBox.Show(String.Format("Cannot parse text '{0}'", text)); 
     continue; // not number was in listview, continue or break 
    } 

    if (value <= tenthousand) 
    { 
      labelVideoViews2.Text = "GREAT"; 
      labelVideoViews2.ForeColor = Color.Green; 
      break; 
    } 
}