0

I'm currently getting the total lates of an employee within a certain period in the format of totalhours and double from a database but the problem is when I check the database and lets say that the employee doesn't have a single record of late which makes reader = null. So, I have decided to use isDBNull but when i insert if (!myReader.IsDBNull(myReader.GetDouble("total"))), the myReader.Getdouble("total") generates an error with an argument that

system cannot convert double to `int

        cc.SetCMD(@"SELECT SUM(AccHours) AS total FROM mia_payroll.tbl_late WHERE COP_ID = @ID AND EID = @EID;");
        using (myConn = new MySqlConnection(ConnectionClass.GetConnection()))
        {
            myConn.Open();
            using (cmDB = new MySqlCommand(cc.GetCMD(), myConn))
            {
                cmDB.Parameters.AddWithValue("@ID", lblCOID.Text);
                cmDB.Parameters.AddWithValue("@EID", EID);
                try
                {
                    using (myReader = cmDB.ExecuteReader())
                    {
                        while (myReader.Read())
                        {
                            if (!myReader.IsDBNull(myReader.GetDouble("total")))
                            {
                                total = myReader.GetDouble("total");
                            }
                            else
                            {
                                total = 0;
                            }
                            txtLate.Text = System.Convert.ToString(total);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            myConn.Close();
        }
M. Adeel Khalid
  • 1,786
  • 2
  • 21
  • 24
Enriko
  • 77
  • 7

3 Answers3

1

This is because .IsDBNull() expects an int ordinal position value of the column that you want to check for DBNULL. You are passing the double value type from myReader.GetDouble(). Official doc: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.isdbnull(v=vs.110).aspx

Simply change to GetOrdinal:

if (!myReader.IsDBNull(myReader.GetOrdinal("total")))
ryancdotnet
  • 2,015
  • 16
  • 33
1

You need to pass the column index to IsDBNull.

Replace !myReader.IsDBNull(myReader.GetDouble("total")) with:

!myReader.IsDBNull(myReader.GetOrdinal("total"))
Serge
  • 3,986
  • 2
  • 17
  • 37
0

what's your datatype for the total field in the database? if your field is not double then you can't parse it as double. The error clearly shows that in your database the field for hours is an int not double,

Abz
  • 1
  • 4