1

I am trying to pull data from database using postgre in C# and putting the values returned in label controls. I keep getting System.InvalidCasaeExeception. The database field is an integer so I a using a data reader to get the value.

here is my code

private void Get_Defects()
    {
        NpgsqlConnection conn = Connection.getConnection();

        try
        {
            conn.Open();
            NpgsqlCommand cmd = new NpgsqlCommand("select * from defect where defect_id >= :MinID and defect_id <= :MaxID and location_id = 102 and top_or_bottom = :TopBottom;", conn);
            cmd.Parameters.Add(new NpgsqlParameter("MinID", MinID));
            cmd.Parameters.Add(new NpgsqlParameter("MaxID", MaxID));
            cmd.Parameters.Add(new NpgsqlParameter("TopBottom", TopBottom));

            NpgsqlDataReader dr = cmd.ExecuteReader();

            if (dr.Read())
            {
                lblCrookedPart.Text = dr.GetInt32(12).ToString();
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        finally
        {
            conn.Close();
        }
    }

}

Not sure why it wont work. I pulled the first element and it displays correctly. some of the data is integers but have null values in the DB. I tried an element with data but I get the cast exception error. Please help.

3 Answers 3

1

Try something like this

NpgsqlDataReader da = default(NpgsqlDataReader);
NpgsqlCommand cmd = new NpgsqlCommand("select * from myTable", GenConnection);
string strVAL = null;
da = cmd.ExecuteReader;
if (da.HasRows) {
    while (da.Read) {
        strVAL = (Information.IsDBNull(da["field"]) ? 0 : da["field"]).ToString;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I got it working, thank you all for you help and tips!!

here is a snippit of the working code

conn.Open();
            NpgsqlDataAdapter da = new NpgsqlDataAdapter("select * from defect where defect_id >= '"+MinID+"' and defect_id <= '"+MaxID+"' and location_id = 102 and top_or_bottom = '"+TopBottom+"';", conn);
            ds.Reset();
            da.Fill(ds);
            dt = ds.Tables[0];

            //Used to sum the column values

            object CrookedPartTotal = dt.Compute("Sum(crooked_part)", "defect_id >= '" + MinID + "' and defect_id <= '" + MaxID + "'");
            if (CrookedPartTotal.ToString() == "")
                lblCrookedPart.Text = "0";
            else
                lblCrookedPart.Text = CrookedPartTotal.ToString();


            object TooMuchSolder = dt.Compute("Sum(too_much_solder)", "defect_id >= '" + MinID + "' and defect_id <= '" + MaxID + "'");
            if (TooMuchSolder.ToString() == "")
                lblTooMuchSolder.Text = "0";
            else
                lblTooMuchSolder.Text = TooMuchSolder.ToString();

Comments

0

You should check that the value is not null. Try the following instead:

lblCrookedPart.Text = (dr.IsDBNull(12)) ? "NULL" : dr.GetInt32(12).ToString();

4 Comments

That takes care of the error but the value is not coming up. I ran a query in postgres and there is 1 but a 0 shows up.(I changed your "NULL" to "0") Do I need to put the result set in an array because I have to sum each defect and display the total in label controls for each defect?
First, are you certain that the column returned in position 12 is the correct one? Why don't you change your select statement to only return the specific column(s) you need. Second, have you ensured that the parameters you are passing contain the correct values?
I figured out half of the problem. I am using a data adaptor and putting into a data table. I can now calculate the sum, however if there are no values, the label control is blank instead of displaying a zero. I am using the compute method an it works but I want to display a zero if there are nulls. Not sure how to check for nulls using a data table. I tried a foreach loop but it does not calculate the sum.
Why not return a 0 in place of a null in your sql select. Take a look at coalesce(). SELECT Coalesce(field_name, 0) AS field_name FROM ....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.