用int.parse添加值

我循环通过一些Excel单元格来总结单元格的值,一些单元格是空的,我得到一个Input string was not in the correct format时,通过它们Input string was not in the correct format错误。 这是我的代码:

  int total = 0; int rowstart = 4; while (ws.Cells[rowstart, 1].Value.ToString() != "") { if (ws.Cells[rowstart, 1].Value.ToString() != ws.Cells[rowstart + 1, 1].Value.ToString()) { ws.InsertRow(rowstart + 1, 1); ws.Cells[rowstart + 1, 3].Value = total; } else { total = total + int.Parse(ws.Cells[rowstart, 3].Value.ToString()); // I'm adding the value of Column 3 to the variable total, I get the error if the cell is empty rowstart = rowstart + 1; } } 

我以为这是因为你不能parsing一个空string,所以如果单元格是空的,我怎么加0呢?

使用int.TryParse

 int parsed; int.TryParse(ws.Cells[rowstart, 3].Value.ToString(), out parsed) total += parsed; 

如果string不是数字,则parsed为0。

使用int.TryParse而不是int.Parse

 int total = 0; int rowstart = 4; while (ws.Cells[rowstart, 1].Value.ToString() != "") { int val=0; if (ws.Cells[rowstart, 1].Value.ToString() != ws.Cells[rowstart + 1, 1].Value.ToString()) { ws.InsertRow(rowstart + 1, 1); ws.Cells[rowstart + 1, 3].Value = total; } else { int.TryParse(ws.Cells[rowstart, 3].Value.ToString(), out val); total = total + val; // I'm adding the value of Column 3 to the variable total, I get the error if the cell is empty rowstart = rowstart + 1; } } 

尝试下面的代码

 else { If (int.TryParse(ws.Cells[rowstart, 3].Value.ToString(), out result)) total = total +int.Parse(ws.Cells[rowstart, 3].Value.ToString()); rowstart = rowstart + 1; }