Click here to Skip to main content
15,888,081 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
please someone help me
I have method that return payments values sum for workers imprests
C#
public static double PaymentsvalueSum(int id)
        {
            string strconn = myproject.Properties.Settings.Default.SalariesConnectionString;
            OleDbConnection conn = new OleDbConnection(strconn);

            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
             OleDbCommand command = new OleDbCommand("select SUM(Payment_Value)from  imprests_payments  WHERE Imprest_ID=@id;", conn);
            command.Parameters.Add(new OleDbParameter("@id", id));
            double sumvalue = (double)command.ExecuteScalar();
            try
            { }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            finally
            {
                conn.Close();
            }
            return sumvalue;
        }

when button_click event I write

 private void button1_Click(object sender, EventArgs e)
        {
           double val = ImprestsPaysMgr.PaymentsvalueSum(int.Parse(GridViewImprestsPays.CurrentRow.Cells["Imprest_ID"].Value.ToString()));
                textBox1.Text = val.ToString();
 }

this code is working perfectly when payments values in imprests_payments table is available but my problem is when no payments values is available in imprests_payments table
where the following error is rising
Object reference not set to an instance of an object.
I need the solution for this problem
Posted
Updated 27-Aug-13 0:30am
v4
Comments
[no name] 27-Aug-13 6:32am    
You are getting that error because you are assuming that your call to ExecuteScalar always returns something.
Marvin Ma 27-Aug-13 6:37am    
You should check the payment values for null before calling your method.

instead of,
C#
double sumvalue = (double)command.ExecuteScalar();

use
C#
double sumvalue = 0;
Double.TryParse(command.ExecuteScalar(),out sumvalue);

Happy Coding!
:)
 
Share this answer
 
When there is no result, the SqlCommand.ExecuteScalar method returns null (see SqlCommand.ExecuteScalar at MSDN[^]).
You may either test for it, e.g.
C#
object obj = command.ExecuteScalar();
if ( obj == null)
{
  // handle the no-result case, for instance set sumvalue=0
}
else
{
  sumvalue = (double) obj;
}


or follow the Aarti Meswania's suggestion and use Double.TryParse. instead
 
Share this answer
 
v2

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