大家好,我在SQL Server 2005数据库中,有一个float类型的数据,可以为空。当时没有赋值。在C#中,我把查询到的值绑定到dataGridView控件中,通过其CellEndEdit事件来编辑更新数据,但是这时候遇到问题。表中的该float类型数据为空,而我在update命令中,要获取这个数据并用于更新。float Ratio = Convert.ToSingle(dataGridView1.Rows[0].Cells[1].Value.Tostring());
该行代码出错,因为这个单元格中没有数据,即为空值!但是空值不能赋给float类型!大家有没有什么好的解决办法啊?
该行代码出错,因为这个单元格中没有数据,即为空值!但是空值不能赋给float类型!大家有没有什么好的解决办法啊?
加个问号代表可空值类型,float?即为Nullable<float>
float Ratio;
if( Convert.ToSingle(dataGridView1.Rows[0].Cells[1]==null)
{
Ration=//默认值
}
else
{
Ratio = Convert.ToSingle(dataGridView1.Rows[0].Cells[1].Value.Tostring());
}
如果你要空值就定义为float?,当DBNull的时候赋值为null
if ( !BNull.(dataGridView1.Rows[0].Cells[1].Value))
{
Ratio = Convert.ToSingle(dataGridView1.Rows[0].Cells[1].Value.Tostring());
}
else
{
Ratio =0;
}