上面的代码抛出一个错误,即对象不能从dbnull转换为其他类型。我试着设置if-else的条件,但没有意义,可能是因为我的问题是我将设置if,else条件,可以检查var\u p\u amount值是否为空,然后lbl\u purchasing\u amount.text=“0”;请帮忙
private void Get_Purchasing_Amount()
{
try
{
double var_P_Amount = 0;
int var_C_Code = 0;
string query = "select c_code as 'code' from `db_vegetable`.`tbl_payment_master`";
DataTable dt_C_Code = method_Class.method_Class.FetchRecords(query);
if (dt_C_Code.Rows.Count > 0)
{
for (int i = 0; i <= dt_C_Code.Rows.Count; i++)
{
var_C_Code = Convert.ToInt32(dt_C_Code.Rows[i]["code"]);
if (var_C_Code.Equals(Convert.ToInt32(txt_Customer_Code.Text)))
{
string get_P_Amount;
if (check_All.Checked.Equals(true))
{
get_P_Amount = "SELECT `purchasing` AS 'purchasing' FROM `db_vegetable`.`tbl_payment_master` WHERE `c_code` = " + txt_Customer_Code.Text + "";
}
else
{
get_P_Amount = "SELECT SUM(t_price) as 'purchasing' FROM `db_vegetable`.`tbl_order_details` WHERE `c_code` = " + txt_Customer_Code.Text + " AND (`date` BETWEEN '" + txt_From_Date.Text + "' AND '" + txt_To_Date.Text + "')";
}
DataTable dt = method_Class.method_Class.FetchRecords(get_P_Amount);
var_P_Amount = Convert.ToDouble(dt.Rows[0]["purchasing"]);
lbl_Purchasing_Amount.Text = var_P_Amount.ToString();
//In this side i use many DBNull methed but it can't be work
//My Question is that If var_P_Amount value is null then
//lbl_Purchasing_Amount.Text = "0";
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
catch (Exception)
{
}
}
2条答案
按热度按时间0ve6wy6x1#
DbNull
在结果集中,表示数据库查询在某个列中返回空值。根据定义,空值不能转换为字符串、数字或任何东西。在您的例子中,结果集中只有一列,它是一个数字。所以零可以代替null而不会对数据造成损坏。
尝试调整查询,使它们永远不会返回null。方法如下:
以及
不过,这只是猜测。你的问题中没有告诉我们程序中哪行代码抛出了异常。
专业提示:永远不要使用
catch (Exception) { }
. 它会导致程序默默地忽略出错的内容。您想知道您的程序何时抛出异常,尤其是当它处理有关其他人资金的数据时。如果必须使用,请执行以下操作:这将有助于防止下一个程序员诅咒你的名字。
ivqmmu1c2#
很可能它在转换为double时失败,所以修复是