?
Solved

Object cannot be cast from DBNull to other types

Posted on 2006-10-24
6
Medium Priority
?
5,602 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 800 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 5

Assisted Solution

by:rameedev
rameedev earned 800 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 400 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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
Suggested Courses
Course of the Month13 days, 23 hours left to enroll

800 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