Click here to Skip to main content
15,897,718 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
double monny = 0;
            try
            {
                if (cn.State.ToString() != "Open")
                    cn.Open();
                cmd = new SqlCommand("select BUY,ADAD from INCREMENT_MADA ", cn);
                dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    monny += Convert.ToDouble(dr["BUY"]) * Convert.ToDouble(dr["ADAD"]);
                }
                
                dr.Close();
                label9.Text = "";
                label9.Text = monny.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
               
                cmd.Cancel();
            }
Posted
Updated 14-Jun-16 2:29am
v2
Comments
ZurdoDev 14-Jun-16 7:28am    
The error seems pretty clear, doesn't it? You're trying to convert null to double. Can't do that.
waleed_akre 14-Jun-16 7:35am    
please check my error and send me thank you....
CHill60 14-Jun-16 7:36am    
Send you what? You can't convert null to a double. What are the values on the database? (hint - at least one of them is null)
waleed_akre 14-Jun-16 7:39am    
please check my code and send me thank you....
CHill60 14-Jun-16 7:47am    
send you what?

You need to check if the values are database nulls before you use them (a database null is not the same as c# null). Something like

C#
while (dr.Read())
 {
  double buy = dr["BUY"] == DBNull.Value ? 0 : Convert.ToDouble(dr["BUY"]);
  double adad = dr["ADAD"] == DBNull.Value ? 0 : Convert.ToDouble(dr["ADAD"]);

 monny += buy * adad;
 }

This code assume you use 0 for the value when it is null, if you want it to do something else then code in whatever logic you want.
 
Share this answer
 
An alternative to Solution 1 - let the SQL do all the work...
C#
double monny = 0;
using (var cn = new SqlConnection(connectionString))
{
    cn.Open();
    var cmd = new SqlCommand("SELECT SUM(ISNULL(BUY,0) * ISNULL(ADAD,0)) AS res FROM INCREMENT_MADA", cn);
    var dr = cmd.ExecuteReader();
    if (dr.Read())
        monny = Double.Parse(dr["res"].ToString());
    dr.Close();
}
label9.Text = monny.ToString();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900