954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Problem updating DB

Hi i keep getting an exception when i'm trying to update table values within a database. the exception is below but i dont change from datetime to varchar it always stay as datetime.

is there any other reasons why this is happening ?

"The conversion of a varchar data type to a datetime data type resulted in an out-of-range value."

objtyp.dtForm  = Convert.ToDateTime(reader["dtFrom"]);

public DateTime dtForm
{
   get;
   set;
}

string SQL = "UPDATE TABLE_NAME SET dtFrom = '" + objtyp.dtForm + "' WHERE ObjectTypeID = 1";


Thanks

Chris

ChrisHunter
Posting Whiz in Training
276 posts since Feb 2011
Reputation Points: 36
Solved Threads: 28
 

You can see from the exception, that your conversation is not ok.
Try to do:

DateTime dateDate = Convert.ToDateTime(reader["dtFrom"]); //column "dtFrom" has to be type of DateTime!


but as it seems from your excetion, your column "dtFrom" is a type of varchar (so string, and no DateTime).
So you can do:

string strDate = (string)reader["dtFrom"];
//if you want some further "date" changing (from whole date-time value to only date for example) you can do:
DateTime dateDate = Convert.ToDateTime(strDate);
strDate = String.Format("{0:MM.dd.yyyy}", dateDate);
//or:
strDate = dateDate.ToShortDateString();


The point is that you have wrong type of columns in the dataBase. If you have dates, times, the type has to be a "DateTime", and notihng else (its very desired). And if we skip this issue, and go back to yours here, conversations arent good enought, and mostly becuase of wrong column types.

Hope this explains your problem - but my code above shoud salve them all anyway - regarldess on wring column types.

Mitja

Mitja Bonca
Nearly a Posting Maven
2,485 posts since May 2009
Reputation Points: 641
Solved Threads: 474
 

Or you could try

DateTime dt = DateTime.Parse((reader["dtFrom"]).ToString());
ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

The Value of dtForm of the column is definatly DateTime. For some reason the column values are formatted like so '000-00-00 00:00:00.000', but will only accept '000-00-00' when updating the column values.

I don't know what the issue is, if it was a format issue it wouldn't allow such a value to be stored in the first place would it ?

I'm okay just storing '000-00-00' for now but would like to know the solution if possible.

Thank you for your help so far.

ChrisHunter
Posting Whiz in Training
276 posts since Feb 2011
Reputation Points: 36
Solved Threads: 28
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: