2014年7月13日 星期日

[RESOLVED] System.InvalidOperationException: Operation is not valid due to the current state of the object on line..


System.InvalidOperationException: Operation is not valid due to the current state of the object on line... if (oDR["CountPO"] == null).


The query gives a null result.



                        try

                        {

                            oDR = cmdx.ExecuteReader();

                            oDR.Read();



                            if (oDR["CountPO"] == null)

                                cntPO = 0;

                            else

                                cntPO = Convert.ToInt32(oDR["CountPO"]);







                            dt2.Rows[i][0] += "  " + cntPO.ToString();





 



You might want to check the HasRows property. Or you might want to use: while (oDR.Read()) etc...



Wrong null. null is not the same as the database null value.


to test for a database null value use:




if(oDR["CountPO"] != DBNull.Value)

or, use the built-in method IsDbNull(). Although this accepts an integer, you can get the integer of a field using GetOrdinal


if(!oDR.IsDbNull(oDR.GetOrdinal("CountPO")))

Don't forget to wrap all the access to the fields in an


if(oDR.Read())
{
// access fields
}



Otherwise if no row is returned this will immediately blow up.





I altered the  code as to the above suggestions... it now skips from the oDR.Read to the brace before the catch missing the code between.


                           oDR = cmdx.ExecuteReader();

                            if (oDR.Read())

                            {



                                if (oDR["CountPO"] != DBNull.Value)

                                {

                                    cntPO = Convert.ToInt32(oDR["CountPO"]);

                               }

                                else

                                    cntPO = 0;



                                dt2.Rows[i][0] += "  " + cntPO.ToString();



                            }

                            



                        }

                        catch (Exception oe)

                        {

                            int y = 0;

                        }



                        finally

                        {

                            if (!oDR.IsClosed)

                                oDR.Close();



                        }



It will because nothing was returned. Just calling Read() on a datareader is not enough, it returns a boolean value for a reason. If oDR.Read() returns false, that means you don't have any data in your datareader and any attempt to read a field returned
will generate an error. Go check the query that is being passed to the database because it isn't returning results. Once you get it to return results then it will get past the check for the read()



Thanks for the comments guys.


沒有留言:

張貼留言