0

I have a date in a DataTable (dt). How to read a Date from a DataTable into a textbox

I can read a string in fine:

    tbEvent.Text = dt.Rows[0].Field<String>(0); 

I tried this but I get an error:

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

        tbDate.Text = dt.Rows[0].Field<DateTime>(1);

Regards Tea

TeaDrinkingGeek
  • 1,995
  • 5
  • 34
  • 52

2 Answers2

2

try

 tbDate.Text = dt.Rows[0].Field<DateTime>(1).ToString();

Textbox.Text only accepts string values - so you need to convert.

Updated

To format the string to show specific values you can use the custom format strings - http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

so the above becomes

 tbDate.Text = dt.Rows[0].Field<DateTime>(1).ToString("dd/MM/yyyy");

for db date 12/23/2012 12:25:45 it will produce 23/12/2012.

Kami
  • 19,134
  • 4
  • 51
  • 63
0

I've been struggling to add my dates correctly on my textbox but finally figured it out

Convert.ToDateTime(dataRow[3].ToString()).ToString("MM/yyyy/dd").ToString();

I changed the format to ("MM/yyyy/dd") instead of ("yyyy/MM/dd")

MarlinG
  • 71
  • 1
  • 1