c# 判断读取字段是否为空,并且赋值
//判断是否为空if (!string.IsNullOrEmpty(dr["ptPrice"].ToString()))
{
product.PtPrice = (decimal)dr["ptPrice"];
}
else
{
product.PtPrice =Convert .ToDecimal ( DBNull.Value) ;
}
我想要判断单价是否为空,如果为空的话,插入数据库空值,但是现在我对单价赋值为空,总会报一个错,无法将dbnull类型转化为其他类型。我该怎么改我的语句啊。 --------------------编程问答-------------------- 你可以用三目 --------------------编程问答-------------------- 多判断一下
if (!string.IsNullOrEmpty(dr["ptPrice"].ToString()) && !(dr["ptPrice"]==DBNULL) )
...
--------------------编程问答-------------------- 很明显这句话有问题,Convert .ToDecimal ( DBNull.Value),DBNULL怎么能ToDecimal呢? --------------------编程问答--------------------
我也知道这句话有错,但是就是不会改,所以请高手帮一下忙。 --------------------编程问答-------------------- if (!string.IsNullOrEmpty(dr["ptPrice"].ToString()))
{
product.PtPrice = (decimal)dr["ptPrice"];
}
else
{
product.PtPrice =0 ;
}
decimal类型变量没有null,只能为零,不知道lz要干嘛,在界面上显示吗?如果是这样就用string类型的吧
if (!string.IsNullOrEmpty(dr["ptPrice"].ToString()))
{
product.PtPrice = dr["ptPrice"].ToString();
}
else
{
product.PtPrice =null ;
} --------------------编程问答-------------------- if (dr["ptPrice"].ToString() != string.empty) --------------------编程问答-------------------- 在页面上显示,如果数据里为空,那在页面上页显示为空值。如果只能为decimal类型,有方法吗? --------------------编程问答-------------------- 设置PtPrice为可空类型
product.PtPrice = dr["ptPrice"]?? DBNull.Vaule; --------------------编程问答--------------------
这个我不知道怎么用,能说明一下嘛 --------------------编程问答-------------------- product.PtPrice = (dr["ptPrice"].ToString() != "")? dr["ptPrice"].ToString() : DBNull.Vaule;
三目运算符 ,可以代替你写的那个if的代码块。 --------------------编程问答-------------------- 要在哪显示?GridView吗?还是TextBox? --------------------编程问答-------------------- 我靠!10楼的,你还真是长得丑啊~~ --------------------编程问答-------------------- 要么空都显示0,要么0都不显示 --------------------编程问答-------------------- public int? PtPrice
{
get;
set;
} --------------------编程问答--------------------
product.PtPrice =dr["ptPrice"].ToString()==""?DBNull:(decimal)dr["ptPrice"];
--------------------编程问答-------------------- 强人太多 --------------------编程问答-------------------- datatable: row.IsNull("")
dataGridView: row.Cells[""] .value == DBNull.Value
--------------------编程问答-------------------- 空值的话存 0 比较好,取的时候可以在前台控制下,不显示 0 就可以了 --------------------编程问答--------------------
这个精炼,顶 --------------------编程问答-------------------- dr["ptPrice"]为空,就不能ToString()。
你先判断dr["ptPrice"]是否为空
--------------------编程问答-------------------- product.PtPrice = dr["ptPrice"]?? DBNull.Vaule; --------------------编程问答-------------------- if (!string.IsNullOrEmpty(dr["ptPrice"].ToString()))
{
product.PtPrice = (decimal)dr["ptPrice"];
}
else
{
product.PtPrice =Convert .ToDecimal ( DBNull.Value) ;
}
不想报错try catch
判断就用if(string.IsNullOrEmpty(dr["ptPrice"]!=null&&DBNull.Value!=null)
你用null来tostring
补充:.NET技术 , C#