【问题标题】:How to retrieve the decimal values from database and store it in a variable and use it in if statement?如何从数据库中检索十进制值并将其存储在变量中并在 if 语句中使用?
【发布时间】: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


【解决方案1】:

根据您编写的基础,可以假设 Product_Amnt 列可以为空。在这种情况下,最好声明 pr_charges 变量,如可为空的 decimal 。 decimal? pr_charges

您可以使用不可为空的,只需将 Null 的 insted 设置为一些默认值,实际上您尝试这样做,但似乎反之亦然。

decimal pr_charges = dr["Product_Amnt"] == DBNull.Value ? 0 : Convert.ToDecimal(dr["Product_Amnt"]);

也请检查enter link description here

enter link description here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多