Reputation: 51
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.
Upvotes: 1
Views: 391
Reputation: 21245
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";
Upvotes: 1
Reputation: 5689
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
Upvotes: 3
Reputation: 32681
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);
Upvotes: 1
Reputation: 15112
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()
Upvotes: 0