1

I am trying to read a date field from database and set it to a label field. Im using the following code,

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
con.Open();

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();
da.Fill(dt);

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 dd-mm-yyyy as 05-02-1991. So I tried the following code:

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

But it shows this error:

No overload for method ToString takes 1 argument

How can I change the format?

2 Answers 2

1

You need to treat your date value as a DateTime and then call the overload of ToString from the DateTime structure that has the required formatting option.

Actually you are converting the row value to a string and a string knows nothing about how to format a date.

DateTime t = dt.Rows[0].Field<DateTime>("Date");
lblName.Text = t.ToString("dd-MM-yyyy");

Also pay attention to the correct format for the Months part. It is an uppercase M. The lowercase m is for minutes.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

Its working im using date format in SQL table..with value 05-02-1991 but in C# when i give format as dd-mm-yyyy it displays in label as 02-05-1991 does this means SQL stores date format as mm-dd-yyyy ??
No, it means the given format string is wrong, it should be dd-MM-yyyy as mm in DateTime formats mean minutes not months.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.