1

I have a date field in a SQL table coming in to a DataGridView in c#. But for some reason, it comes with a time too, even though its just a date field.

Image

4 Answers 4

3

Keep your DateTime object as a DateTime. The DataGridView offers a format string property where you can format your DateTime object as you wish.

This will get you started on formatting dates - http://msdn.microsoft.com/en-us/library/az4se3k1.aspx

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

Comments

1

in case you want it in any specific format Do it like this

 string format = "dd/MM/yyyy";
 string dateOnly = dt.ToString(format, CultureInfo.InvariantCulture);

and in case your database is returning string you have to do this as well

 DateTime dt = DateTime.ParseExact(yourDateTimeString, "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

Comments

1

As part of your Data Binding object for the DataGridView make the property a string.

public class DataBindingObj
{
    public string DateRemoved { get; set; }
}

Use DateTime.ToShortDateString.

This will return the culture specific formatting (M/d/yyyy for en-US).

var bindingObjs = new List<DataBindingObj>();

foreach(var obj in dataFromDatabase)
{
    var bindingObj = new DataBindingObj { DateRemoved = obj.DateRemoved.ToShortDateString() };
    bindingObjs.Add(bindingObj);
}

dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = bindingObjs;

Edit: From the comments it seems DataGridView has a property for that:

public class DataBindingObj
{
    public DateTime DateRemoved { get; set; }
}

dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = bindingObjs;
dataGridView1.Columns["DateRemoved"].Format = "d";

1 Comment

There is no need to make the property a string. You will have more control of it as a DateTime object. The DataGridView has a property to set a format string. setting it to 'd' will do the trick.
0

12:00:00 AM is the default time for DATETIME types in C# if time is not specified.

To get only the date use dateTime.ToShortDateString()

Comments

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.