Solved

Object cannot be cast from DBNull to other types

Posted on 2006-10-24
6
5,576 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
[X]
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
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

695 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