Solved

Object cannot be cast from DBNull to other types

Posted on 2006-10-24
6
5,482 Views
Last Modified: 2008-01-09
I am trying to convert DateTime after retrieving a row using stored proceduce as follows

        //get single product
        public Product GetProduct(int ProductID)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("usp_SelectProduct");
            SqlParameter[] p = new SqlParameter[1];
            p[0] = new SqlParameter("@P_Productid", SqlDbType.Int);
            p[0].Value = ProductID;
            DataRow row = Db.GetDataRow(sql.ToString(), p);
            int productid = int.Parse(row["P_ProductID"].ToString());
              ...
            decimal  Reorderlevel = decimal.Parse(row["P_ReorderLevel"].ToString());
            string  Warehouseno = row["P_WareHouseNo"].ToString();
            DateTime  Modifieddate = Convert.ToDateTime(row["P_ModifiedDate"]);
            string Memo = row["P_Memo"].ToString();
            string Desc = row["P_Desc"].ToString();
            Product product;
            return product = new Product(productid, Productname, Qtyperunit, Unitprice, Unitsinstock, Unitsonorder, Reorderlevel, Warehouseno, Modifieddate, Memo, Desc);
        }

but I get an error saying:

===============================================================================================================================
Object cannot be cast from DBNull to other types.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Object cannot be cast from DBNull to other types.

Source Error:


Line 103:            decimal  Reorderlevel = decimal.Parse(row["P_ReorderLevel"].ToString());
Line 104:            string  Warehouseno = row["P_WareHouseNo"].ToString();
Line 105:             DateTime  Modifieddate = Convert.ToDateTime(row["P_ModifiedDate"]);
Line 106:            string Memo = row["P_Memo"].ToString();
Line 107:            string Desc = row["P_Desc"].ToString();
 

Source File: C:\IList_WareHouse_Solution\DataObjects\SqlServer\SqlServerProductDao.cs    Line: 105
===============================================================================================================================

then I tried the following:

            object Modifieddate_obj = row["P_ModifiedDate"];
            if (Modifieddate_obj != System.DBNull.Value)
            {
                Modifieddate = Convert.ToDateTime();
            }

but that doesn't work either.  I don't know how to deal with this DateTime.  The current contains the value {}.   Can I return 00/00/00 00:00:00 if datetime is blank?  This Modifieddate is going to be displayed in detailsview control.

thanks
Nick
0
Comment
Question by:countyprob
6 Comments
 
LVL 8

Expert Comment

by:bramsquad
ID: 17798295
Modifieddate = Convert.ToDateTime(Modifieddate_obj);

~b
0
 
LVL 1

Author Comment

by:countyprob
ID: 17799498
Ok I tried that but now I get:

Error      11      Use of unassigned local variable 'Modifieddate'      C:\IList_WareHouse_Solution\DataObjects\SqlServer\SqlServerProductDao.cs      119      144      DataObjects


it is having a problem with variable in my return statement


           string  Warehouseno = row["P_WareHouseNo"].ToString();
            DateTime Modifieddate;
            object Modifieddate_obj = row["P_ModifiedDate"];
            if (Modifieddate_obj != System.DBNull.Value)
            {
                Modifieddate = Convert.ToDateTime(Modifieddate_obj);
            }
            string Memo = row["P_Memo"].ToString();
            string Desc = row["P_Desc"].ToString();
            Product product;
            return product = new Product(productid, Productname, Qtyperunit, Unitprice, Unitsinstock, Unitsonorder, Reorderlevel, Warehouseno, Modifieddate, Memo, Desc);

Why would it complain if I already defined Modifieddate as DateTime type?

nick
0
 
LVL 8

Accepted Solution

by:
bramsquad earned 200 total points
ID: 17800657
the reason is becuase when you return you include the variable 'Modifieddate' however, you only assign a value to it when 'Modifieddate_obj' is not equal to null.   So when it is null and you dont assign a value to it, itll give that error.

So you have to make sure you assign a value to the variable.  Just do it at declaration.

DateTime Modifieddate = DateTime.MinValue;

this will set it to the min value (1/1/0001 12:00:00 AM)

this way you can always check for that and act accordingly

~b
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 5

Assisted Solution

by:rameedev
rameedev earned 200 total points
ID: 17802109
Can you try checking for a simple null something like this

DateTime Modifieddate;
if(!row["P_ModifiedDate"]==null)
{
    Modifieddate = Convert.ToDateTime(Modifieddate_obj);
}
0
 
LVL 29

Assisted Solution

by:Gautham Janardhan
Gautham Janardhan earned 100 total points
ID: 17802981
string  Warehouseno = row["P_WareHouseNo"].ToString();
                  DateTime Modifieddate = Datetime.MinValue;
                  
                  if (!row.IsNull("P_ModifiedDate"))
                  {
                        Modifieddate = Convert.ToDateTime(Modifieddate_obj);
                  }
                  string Memo = row["P_Memo"].ToString();
                  string Desc = row["P_Desc"].ToString();
                  return new Product(productid, Productname, Qtyperunit, Unitprice, Unitsinstock, Unitsonorder, Reorderlevel, Warehouseno, Modifieddate, Memo, Desc);
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
ID: 17802984
assuming row is DataRow
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
Both in life and business – not all partnerships are created equal. As the demand for cloud services increases, so do the number of self-proclaimed cloud partners. Asking the right questions up front in the partnership, will enable both parties …

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now