日期:2014-05-18  浏览次数:21355 次

C# Convert.toDouble()为空值时报错
如题。
C# code

#region 实现最后一行合计函数
        public void TotalRow(DataGridView dataGridview1)
        {
            DataGridViewRow dgr = dataGridview1.Rows[dataGridview1.Rows.Count - 1];
            dgr.ReadOnly = true;
            dgr.DefaultCellStyle.BackColor = System.Drawing.Color.Khaki;
            dgr.Cells[0].Value = "合计";
            double db;
          
            for (int i = 0; i < dataGridview1.Rows.Count - 1; i++)
            {
                    try
                    {
                        db = Convert.ToDouble(dgr.Cells[4].Value) + Convert.ToDouble(dataGridview1.Rows[i].Cells[4].Value ??1);
                        dgr.Cells[4].Value = db.ToString("#0.00");                    }
                    catch (Exception ex)
                    { MessageBox.Show(ex.Message); }

            }
        }
        #endregion


datagridview1控件最后一行取合计,累计加第五列的数据,可当单元格无值的时候会提示“输入字符串的格式不正确”,请教各位大侠。

------解决方案--------------------
for (int i = 0; i < dataGridview1.Rows.Count - 1; i++)
{
try
{
if(String.IsNullOrEmpty(dgr.Cells[4].Value.ToString()))
{
MessageBox.Show("数据为空!");
return;
}
db = Convert.ToDouble(dgr.Cells[4].Value.ToString()) + Convert.ToDouble(dataGridview1.Rows[i].Cells[4].Value ??1);
dgr.Cells[4].Value = db.ToString("#0.00"); }
catch (Exception ex)
{ MessageBox.Show(ex.Message); }

}
------解决方案--------------------
探讨

引用:
for (int i = 0; i < dataGridview1.Rows.Count - 1; i++)
{
try
{
if(String.IsNullOrEmpty(dgr.Cells[4].Value.ToString()))
{
MessageBox.Show("数据为空!");
return;
}
db = Con……

------解决方案--------------------

先对dgr.Cells[4].Value做非空验证

再对它进行转换操作
------解决方案--------------------

先对dgr.Cells[4].Value做非空验证

然后再对它进行转换操作
------解决方案--------------------
public void TotalRow(DataGridView dataGridview1)
{
DataGridViewRow dgr = dataGridview1.Rows[dataGridview1.Rows.Count - 1];
dgr.ReadOnly = true;
dgr.DefaultCellStyle.BackColor = System.Drawing.Color.Khaki;
dgr.Cells[0].Value = "合计";
double db;

for (int i = 0; i < dataGridview1.Rows.Count - 1; i++)
{
try
{

//
db = Convert.ToDouble(dgr.Cells[4].Value==""? 0:dgr.Cells[4].Value) + Convert.ToDouble(dataGridview1.Rows[i].Cells[4].Value==""?0:dataGridview1.Rows[i].Cells[4].Value);

dgr.Cells[4].Value = db.ToString("#0.00"); }
catch (Exception ex)
{ MessageBox.Show(ex.Message); }

}
}
------解决方案--------------------
for (int i = 0; i < dataGridview1.Rows.Count - 1; i++)
{
try
{
double value1="";
double value2="";