读书人

C# Convert.toDouble()为空值时报错解

发布时间: 2012-03-25 20:55:17 作者: rapoo

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="";


if(!string.isNullOrEmpty(dgr.Cells[4].Value))
{
Convert.ToDouble(dgr.Cells[4].Value)
}
if(!dataGridview1.Rows[i].Cells[4].Value))
{
value2=Convert.ToDouble(dataGridview1.Rows[i].Cells[4].Value ??1
}
db = value1+value2;
dgr.Cells[4].Value = db.ToString("#0.00"); }
catch (Exception ex)
{ MessageBox.Show(ex.Message); }

}

读书人网 >C#

热点推荐