Click here to Skip to main content
15,912,578 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was writen a function to retrive the price from database,
XML
I got error say this line have problem:<b>price = (decimal) cmd.ExecuteScalar(); </b>
I supporse will get one result back.
<b>Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. </b>


here is my function
public decimal LMQuery(string vehicleCatID,string postCode,string suburb,string state,string city)
        {
            string CS = ConfigurationManager.ConnectionStrings["DBLM3"].ConnectionString;
            using (SqlConnection con = new SqlConnection(CS))
            {
                decimal price = decimal.Zero;
                
                string sqlQuery = string.Empty;

                sqlQuery = "my query is running correct in sql server management";


                SqlCommand cmd = new SqlCommand(sqlQuery,con);

                con.Open();
                price = (decimal) cmd.ExecuteScalar();
                
                return price;             

            }
        }
Posted
Comments
Praveen Kumar Upadhyay 8-Jan-15 1:38am    
1) price = (decimal) cmd.ExecuteScalar();
might be giving error. Please check what is the result of cmd.ExecuteScalar() before converting it to decimal.
2) ConfigurationManager.ConnectionStrings["DBLM3"].ConnectionString;
This line can also give error, check id there is a connection section with the above name.
Thava Rajan 8-Jan-15 4:19am    
on which line the error occureed

Quote:
"my query is running correct in sql server management"

Doesn't look a valid SQL query, to me.
 
Share this answer
 
Comments
Rahul Gupta (Robin) 8-Jan-15 4:21am    
during the conversion only this error should come... other code look like ok.
Thanks everyone, I already solved that problems. Just before I assign it to my price,I should check it empty or not.

cmd.ExecuteScalar(); can return empty result.
 
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