2
votes

Hi all I am reading data from sql server using stored procdure, and everything looks excpet when there is a null data in the database I get cannot cast DBNull to other types. I am using .net MVC3 following is my code:

public static List<XYZFactorsModel> SelectGridItems(string sidx, string sord, int page, int rows, String rid, String process, String detail_table, String jobGroup, String date)

    {


       const string spName = "dbo.p___GetXYZMonitorJobDetails";
        List<XYZFactorsModel> XYZFactorDetailGridCollection;

        string connectionString = ConfigurationManager.ConnectionStrings["AdvItemsContext"].ConnectionString;
        if (string.IsNullOrEmpty(connectionString))
            return null;
        using (SqlConnection sqlConnection = new SqlConnection(connectionString))
        {
            SqlCommand sqlCommand = new SqlCommand(spName, sqlConnection);
            sqlCommand.CommandType = CommandType.StoredProcedure;
            //sqlCommand.Parameters.Add("@jobDate", SqlDbType.VarChar);
            sqlCommand.Parameters.Add("@jobGroup", SqlDbType.VarChar);
            sqlCommand.Parameters.Add("@jobName", SqlDbType.VarChar);
            sqlCommand.Parameters.Add("@detailTable", SqlDbType.VarChar);
            sqlCommand.Parameters.Add("@filterBatchControl", SqlDbType.VarChar);
            sqlCommand.Parameters.Add("@filterDate", SqlDbType.VarChar);
            sqlCommand.Parameters.Add("@filterTime", SqlDbType.VarChar);

            //sqlCommand.Parameters["@jobDate"].Value = date2;
            sqlCommand.Parameters["@jobGroup"].Value = jobGroup;
            sqlCommand.Parameters["@jobName"].Value = process;
            sqlCommand.Parameters["@detailTable"].Value = detail_table;
            sqlCommand.Parameters["@filterBatchControl"].Value = rid;
            sqlCommand.Parameters["@filterDate"].Value = date;
            sqlCommand.Parameters["@filterTime"].Value =date;

            sqlConnection.Open();
            XYZFactorDetailGridCollection = FillGridEntity(sqlCommand);
        }
        return XYZFactorDetailGridCollection;
    }

    private static List<XYZFactorsModel> FillGridEntity(SqlCommand sqlCommand)
    {
        List<MBSFactorsModel> thegrid = new List<MBSFactorsModel>();
        using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
        {
            while (sqlDataReader.Read())
            {
               try
                {

                    //if(sqlDataReader["last_factor"] != System.DBNull.Value)
                   //{
                   //    
                   //    thegrid.Add(new XYZFactorsModel
                   //    {
                   //        last_factor = Convert.ToDateTime(sqlDataReader["last_factor"])
                   //    });
                   //}
                   //else
                   //{
                   //    System.Diagnostics.Debug.WriteLine("null value was found in last factor field");
                  // }

                    thegrid.Add(new XYZFactorsModel
                    {
                        abc = sqlDataReader["abc"].ToString(),
                        abc2 = sqlDataReader["abc2"].ToString(),
                        abc3 = sqlDataReader["abc3"].ToString(),
                        abc4 = sqlDataReader["abc4"].ToString(),
                        abc5 = Convert.ToDecimal(sqlDataReader["abc5"]),
                 last_factor = Convert.ToDateTime(sqlDataReader["last_factor"]),

                    });


                }
                catch (Exception ex)
                {

                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }

            }
        }
        return thegrid;
    }
}
3

3 Answers

0
votes

You need to check SqlDataReader.IsDBNull before assigning to a non-nullable type. If that returns true you need to decide how you want to initialize your non-nullable variable. After all, things like int and decimal cannot have a null value assigned to them.

Gets a value that indicates whether the column contains non-existent or missing values.

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.isdbnull.aspx

0
votes

You aren't showing the declaration of your variables, but I suspect the issue is in the lines which pull the data out of the sqlDataReader instance:

last_factor = Convert.ToDateTime(sqlDataReader["last_factor"])

If last_factor is declared as DateTime last_factor;, and the column is null, the Convert call will fail. You would need to check to see if IsDbNull is true prior to making this conversion.

If null values are appropriate, I would recommend using a nullable type here instead:

DateTime? last_factor = sqlDataReader.IsDbNull(columnNumber) ? (DateTime?)null : sqlDataReader.GetDateTime(columnNumber);
0
votes

just converted all the data types to string and now it works fine.