Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Object cannot be cast from DBNull to other types

Posted on 2006-10-24
6
5,530 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
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
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…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

809 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