Mano Prathibhan C Mano Prathibhan C - 8 months ago 41
SQL Question

Change date format in C# when reading from database and setting to label

I am trying to read a

field from database and set it to a label field. Im using the following code,

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand("select BirthDate from Student where Name=@name", con);
cmd.Parameters.AddWithValue("@name", "Mano");
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
lblName.Text = dt.Rows[0]["Date"].ToString();

But this displays the data value in label in the format
02-05-1991 00:00:00
but i want to display it in format
. So i tried the following code,

lblName.Text = dt.Rows[0]["BirthDate"].ToString("dd-mm-yyyy");

But it shows following error,

No overload for method ToString takes 1 argument

How can i change format?


Assuming BirthDate represents a valid DateTime, convert it before calling ToString().

lblName.Text = Convert.ToDateTime(dt.Rows[0]["BirthDate"]).ToString("dd-mm-yyyy");

You're currently calling the ToString() method on the object class, not the DateTime class, so there's no overload that allows for a date formatter.