Solved

Object cannot be cast from DBNull to other types

Posted on 2006-10-24
6
5,458 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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
I need C# converted to VB.net 1 52
Default parameter problem in C# 3 27
dynamic menu in asp.net c# 11 27
C# TextBox 11 12
Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

706 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

17 Experts available now in Live!

Get 1:1 Help Now