Search code examples
c#xamppdoublemysqldatareader

reader.GetDouble needs int?


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();
        }

Solution

  • 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")))