【发布时间】:2015-03-13 04:45:53
【问题描述】:
我在 Sql server 中有一个存储过程。这个 sp 返回一个数据集(有 49 列)。数据集中有一列“Product_Amnt”具有十进制值。
我正在尝试使用 c# 在 asp.net 应用程序中检索此列数据。
DataTable dt = new DataTable();
try
{
SqlCommand com = new SqlCommand("sp_ProductDetails");
com.CommandType = CommandType.StoredProcedure;
com.Connection = con;
com.Parameters.Add("@ID", SqlDbType.Int).Value = this._ID;
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(dt);
}
catch (Exception ex) { new Error(ex); }
return dt;
我想使用“Product_Amnt”列根据条件显示产品。
decimal pr_charges = Convert.ToDecimal(dr["Product_Amnt"]);
但是它给出了一个错误,说“对象不能从 dbnull 转换为其他类型”。于是我就这样修改了代码,
decimal pr_charges = dr["Product_Amnt"] == DBNull.Value ? 0 : Convert.ToDecimal(dr["Product_Amnt"]);
if (pr_charges == 0.00M)
{
counter++;
}
但它总是给我 pr_charges 变量中的值 0。
如何从数据库中检索十进制值并将其存储在变量中?
【问题讨论】:
-
您的数据是否有除 null 和 0 以外的值?
-
是的,比如 150.00 和 364.75
-
将您的数据放入网格中或将其打印到控制台,以确保您恢复了您的想法。你没有选角问题; DBNull 就是这样,null。当您比较
dr["Product_Amnt"] == DBNull.Value并得到 0 时,这是因为您在该列中的数据 is null -
当您在调试器中停止代码并查看返回的 dataTable 中的数据时,您会在该列中看到 NULL 以外的值?还是您只是假设它们在那里,因为它们在您的数据库中?
标签: c# asp.net sql-server