繁体   English   中英

输入的字符串格式不正确

[英]Input string was not in a correct format

为什么会出现错误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;
}

当您向其传递不是数字的字符串时, 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
}

您的字符串很可能包含int以外的其他字符,例如字母甚至点

在进行转换之前,请调试您的应用,并确保实际上只有数字

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

我认为您不需要将整数转换为字符串并将其解析回:

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;
     }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM