[英]Error: 'Input string was not in a correct format.'
int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count;++i)
{
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
}
label1.Text = sum.ToString();
以上是计算的代码。 当我运行应用程序时,它没有显示任何错误。 从 MySql 加载 datagridview 并按下导致上述功能的按钮后,它显示错误。
System.FormatException: '输入字符串的格式不正确。'
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
如果我将 Cells[2] 更改为 Cells[0] 它工作正常
我仍然是 C# 初学者,但我猜它无法将“earned”列中的数据转换为整数?
考虑到您的屏幕截图, Cells[2]
不是int
而是Decimal
和 sum 应声明为此类类型。
Decimal sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count;++i)
{
sum += Decimal.Parse((dataGridView1.Rows[i].Cells[2].Value ?? "").ToString());
}
如果由于某些原因该值为空或错误,则可以使用TryParse来检查转换是否成功:
Decimal sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count;++i)
{
Decimal temp;
if (Decimal.TryParse((dataGridView1.Rows[i].Cells[2].Value ?? "").ToString(), out temp))
sum += temp;
}
label1.Text = sum.ToString();
注意: (dataGridView1.Rows[i].Cells[2].Value ?? "")
将对dataGridView1.Rows[i].Cells[2].Value
执行检查。 如果它为 null,则将使用值""
而不是null
。 null.ToString()
将抛出异常。
您应该检查该字段是否具有数值,然后将其转换为 int。
float sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count;++i)
{
float temp = 0;
float.TryParse(dataGridView1.Rows[i].Cells[2].Value?.ToString(), out temp);
sum += temp;
}
label1.Text = sum.ToString();
试试这个
Decimal sumcol = 0;
for (int i = 0; i < dataGridView1.Rows.Count;++i)
{
Decimal val;
string colval = dataGridView1.Rows[i].Cells[2].Value.ToString();
if(colval != null){
if (Decimal.TryParse(colval, out val))
sum += val;
}
label1.Text = sum.ToString();}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.