Kelvin Ong
Kelvin Ong

Reputation: 19

Remove Time from DateTime

I got a DataTable that retrieves DateTime from SQL. However, I want to show date only in my textbox. I try to convert but compile time error keep saying

no overload for method ToString takes 1 argument.

txtexpiry.Text = dtbl.Rows[0]["Safetyexpirydate"].ToString("dd/MM/yyy");

Upvotes: 1

Views: 947

Answers (5)

user9405863
user9405863

Reputation: 1514

Convert data row object to DateTime and check object for non-null condition with simple ternary (?) operator before doing type casting.

txtexpiry.Text = dtbl.Rows[0]["Safetyexpirydate"] != null 
  ? ((DateTime)dtbl.Rows[0]["Safetyexpirydate"]).ToString("dd/MM/yyy")
  : "";

Upvotes: 0

EricImhauser
EricImhauser

Reputation: 791

txtexpiry.Text = String.Format("{0:dd/MM/yyyy}", dtbl.Rows[0]["Safetyexpirydate"]);

Upvotes: 0

Oscar
Oscar

Reputation: 13990

Assuming Safetyexpirydate is already a DateTime type:

txtexpiry.Text = ((DateTime) dtbl.Rows[0]["Safetyexpirydate"]).Date

Upvotes: -3

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

You should Convert it and when you get DateTime instead of Object call required ToString():

txtexpiry.Text = Convert
  .ToDateTime(dtbl.Rows[0]["Safetyexpirydate"]) // we have DateTime
  .ToString("dd/MM/yyy");                       // which we represent as "dd/MM/yyy" 

Upvotes: 4

Patrick Hofman
Patrick Hofman

Reputation: 157118

dtbl.Rows[0]["Safetyexpirydate"] returns object, and that doesn't have that overload. DateTime does, so you have to cast the object to DateTime:

txtexpiry.Text = ((DateTime)dtbl.Rows[0]["Safetyexpirydate"]).ToString("dd/MM/yyy");

If the object can be null, you have to check that first. The easiest way in this case is to use is:

 object o = dtbl.Rows[0]["Safetyexpirydate"];

 if (o is DateTime d)
 {
     txtexpiry.Text = d.ToString("dd/MM/yyy");
 }

Upvotes: 4

Related Questions