Reputation: 8419
Example : I get myDataTable from database through some query (Lot of different queries) and want to change the Date
and DateTime
fields to user desired presentation.
void dgv_DataSourceChanged(object sender, EventArgs e)
{
for (int i = 0; i < dgv.Columns.Count; i++)
{
if (myDataTable.Columns[i].DataType == typeof(DateTime))
dgv.Columns[i].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
else
{
if (myDataTable.Columns[i].DataType == typeof(Date))
dgv.Columns[i].DefaultCellStyle.Format = "dd-MM-yyyy";
}
}
}
You can see there is no problem with columns having DataType=DateTime
, but how can I handle the Date
dataType regardless of my current database query? Date is available in database but not in c#.
Update : I can do this through checking the ending of date value weather it is 12:00: AM or 00:00:00. But this seems a bogus solution a real DateTime value can also have the same value. This value does not guarantee that DataType is Date
and not DateTime
Upvotes: 2
Views: 16702
Reputation:
Perhaps you can not distinguish. What you can do in this particular case is
for (int i = 0; i < dgv.Columns.Count; i++)
{
if (source.Columns[i].DataType == typeof(DateTime))
{
string val = source.Rows[0][i].ToString();
if (val.EndsWith("12:00:00 AM") ||val.EndsWith("00:00:00"))
{
dgv.Columns[i].DefaultCellStyle.Format = "yyyy-MM-dd";
//Your date Format
}
else
dgv.Columns[i].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
//Your date and Time Format
}
}
Upvotes: 1
Reputation:
foreach( DataRow dr in datatable.Rows)
{
DateTime dt = DateTime.ParseExact(dr["YourDateTimeColumnName"],
"MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
string s = dt.ToString("dd/M/yyyy");
}
now your DateTime is converted to Date and you can use it in DataGridView.
Upvotes: 2
Reputation: 16698
There is only DateTime datatype available in C# for datetime, date datatype of SQL Sever.
See the following datatype mapping table for reference: SQL Server Data Type Mappings
Upvotes: 0