Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 503
  • Last Modified:

Error: Cast from string "" to type 'Date' is not valid.

I'm receiving the following error when trying to do an update back to a database:
Cast from string "" to type 'Date' is not valid.
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: Cast from string "" to type 'Date' is not valid.

Source Error:

Line 606:        cmdHomeCompliance.Parameters.Add("@DiaryDone", SqlDbType.Int, 4).Value = HomeCompliance.DiaryDone
Line 607:        cmdHomeCompliance.Parameters.Add("@PT", SqlDbType.Int, 4).Value = HomeCompliance.PT
**Line 608:        cmdHomeCompliance.Parameters.Add("@PTDCDate", SqlDbType.DateTime, 8).Value = CDate(HomeCompliance.PTDCDate)
Line 609:        cmdHomeCompliance.Parameters.Add("@OT", SqlDbType.Int, 4).Value = HomeCompliance.OT
Line 610:        cmdHomeCompliance.Parameters.Add("@OTDCDate", SqlDbType.DateTime, 8).Value = CDate(HomeCompliance.OTDCDate)
Source File: j:\inetpub\wwwroot\db\chae01\HomeComplianceDB.vb    Line: 608

HomeCompliance.PTDCDate is a string, but I need to store it back in the database as a date.  Sometimes it will not be filled in, and will be "" instead.  I'm not sure how to handle that situation in this section of the code.

Any suggestions on how I can fix this?  Thanks!
2 Solutions
Hi, you have to validate your data:
If HomeCompliance.PTDCDate="" Then
' use a default datetime for example: DateTime.Now
cmdHomeCompliance.Parameters.Add("@PTDCDate", SqlDbType.DateTime, 8).Value = DateTime.Now
cmdHomeCompliance.Parameters.Add("@PTDCDate", SqlDbType.DateTime, 8).Value = CDate(HomeCompliance.PTDCDate)

suppose u got form with one text box which takes date

if user try to enter empty text to it, database will throw cast error
to prevent this check value of text if it is null then set value to nothing

for example

if textbox.text <> "" then
     yourcolumn.value = Convert.ToDateTime(textbox.text)
     yourcolumn.value = nothing
end if

hope this will help you

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now