当查询返回null到十进制值时,输入字符串不是正确的格式 [英] Input string not in correct formate when query return null to decimal value

查看:127
本文介绍了当查询返回null到十进制值时,输入字符串不是正确的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

将null转换为十进制时,错误输入字符串不正确格式化 

when convert null to decimal i get error input string not in correct formate 

如何解决

public static object ExecuteScalar(string sql, DbParameter[] @params = null)
    {
        if (sql == "") return "";
        object result = null;

        lock (synObj)
        {
    
            sql = AnalyizeBooleanFields(sql);
            cmd.CommandText = sql;
            cmd.Parameters.Clear();

            if (@params != null)
            {
                for (int i = 0; i < @params.Length; i++)
                {
                    cmd.Parameters.Add(@params[i]);
                }
            }

            if (Connection.State != ConnectionState.Open) Connection.Open();

            if (WithTransaction) cmd.Transaction = _transaction;

            
          
            result = cmd.ExecuteScalar();

            if (!WithTransaction) Connection.Close();
            }

        return (result == null || result == DBNull.Value) ? "" : result;
    }

  private decimal GetLastReading(string UnitCode, string Year, string Month)
        {
            string sqlquery = "";
            if (txtMonth.Text == "1")
            {
                sqlquery = "select CurrentMeterReading from WAHInvoice where UnitCode=" + UnitCode + " and Month = 12 And Year =" + (Convert.ToInt32(Year) - 1).ToString() + "";
            }
            else
            {
                sqlquery = "select CurrentMeterReading from WAHInvoice where UnitCode='" + UnitCode + "' and Month = '" + (Convert.ToInt32(Month) - 1).ToString() + "' And Year ='" + Year + "'";
            }
          
            return ConvertToDecimal(DataAccess.ExecuteScalar(sqlquery));
        }

当我按以下方式调用时

       decimal LastMeterReading = GetLastReading(dt.Rows[i]["UnitCode"].ToString(), txtYear.Text, txtMonth.Text).ToString();

现在如果sqlquery没有返回任何行,它会让我从函数中获取异常  GetLastReading

Now if sqlquery not return any row it give me exception from function  GetLastReading

当查询返回null到十进制值时,输入字符串的格式不正确。

Input string not in correct format when query return null to decimal value .

这样如何避免这个错误。

so that how to avoid this error please .

推荐答案

嗨艾哈迈德,

为什么不试着检查首先为null或空值,然后执行操作。希望这会对你有所帮助。

Why not try to check for null or empty value first then do the operation. Hope this will helps you.

if(!string.IsNullOrEmpty()) 
{
   //Do the task
}


这篇关于当查询返回null到十进制值时,输入字符串不是正确的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆