Share via


Unable to cast object of type 'System.DateTime' to type 'System.String'.

Question

Saturday, February 16, 2008 10:35 AM

Hi All,

  I'm struggling with this one so maybe someone can help me out... I have a date time field in a db table and I want to add it to a text box.  Seems like such a simple task but it's kicking my butt.  I did some google'n but didn't find anything less simple or more confusing.   Someone please help...  

Here's what I have...   dr is a datareader

txtOpenOn.Text = String.Format((String)dr["open_date"], "{0:MM/dd/yyyy}");

thanks
rich

All replies (4)

Saturday, February 16, 2008 11:20 AM ✅Answered

Try:

txtOpenOn.Text = ((DateTime)dr["open_date"]).ToString("MM/dd/yyyy");


Saturday, February 16, 2008 3:04 PM ✅Answered

 

txtobject.text = dr["nullfield"] as string ?? String.Empty;

 


Saturday, February 16, 2008 12:28 PM

that work awesome... thank you...  Is there another way to skip over nulls?  I was also getting an error if the field was null... ie:

 

db field is null

txtobject.text = (String) dr["nullfield"];   - would give me an error can not cast string to type null  any suggestions?

 

Right now I'm passing the db filed to a function and it seems like to much work to skip over a null field...

public string getValue(object PassValue)

{

if (!(PassValue == null))

{

return Convert.ToString(PassValue);

}

else

{

return "";

}

-rich


Sunday, February 17, 2008 9:27 AM

  

int idx = dr.GetOrdinal("myfield");
if (!dr.IsDBNull(idx))
{
  // read value here
}