0

I am trying to get the sum of total hours in a database. but while creating a new one there won't be any previous hours to calculate. Here is the following code:

private void calculateflyinghours()
{
    string ConString = " datasource = localhost; port = 3306; username = root; password = 3306";
    string Query = " Select sum(Flying_Hours)from aircraft." + Form1.a;

    MySqlConnection ConDatabase = new MySqlConnection(ConString);
    MySqlCommand cmdDataBase = new MySqlCommand(Query, ConDatabase);

    MySqlDataReader myReader;

    ConDatabase.Open();

    myReader = cmdDataBase.ExecuteReader();

    while ((myReader.Read()))
    {

        sum.Text = Convert.ToString(double.Parse(myReader.GetString(0)));
        progressBar1.Increment(1);
    }
    myReader.Close();
}

I get the Following error while trying to open a new database with no data inserted :

Data is Null. This method or property cannot be called on Null values. At the sum.Text = Convert.ToString(double.Parse(myReader.GetString(0)));

UPDATE: the code should be:

if (!myReader.IsDBNull(0)) { sum.Text = (double.Parse(myReader.GetString(0))).ToString(); }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
guetty abboud
  • 31
  • 2
  • 7
  • So you're trying to get a value from the db (`myReader.GetString(0)`) and have no values in the db... what did you expect? – EpicKip Jul 19 '17 at 09:08
  • 1
    You need to check with `if (!myReader.IsDBNull(0)) { (double.Parse(myReader.GetString(0))).ToString() }` before getting string from it. – Tetsuya Yamamoto Jul 19 '17 at 09:09
  • you want to read a string, parse it to double and convert it back to a string? – Fabiano Jul 19 '17 at 09:11
  • Why are you fetching the value as a string and then parsing it at all? And why use `ExecuteReader` rather than `ExecuteScalar`? – Jon Skeet Jul 19 '17 at 09:11

0 Answers0