Hi tejunguasu,
You can actually do this through the designer. Open the Columns collection for the DataGridView and expand the DefaultCellStyle and set the Format property. You can even select it from a list.
Using the designer assumes that you are not autopopulating the columns collection of your DataGridView. If you are autopopulating, you can examin the designer generated code when you add a column and set it's format.
The following code uses a prepopulated 3 column DataGridView bound to a DataTable with three DateTime columns and using the above advice to set their formatting dynamically.
private void Form1_Load(object sender, EventArgs e)
{
DataTable DT = new DataTable();
DT.Columns.Add("DT", typeof(DateTime));
DT.Columns.Add("JustDate", typeof(DateTime));
DT.Columns.Add("JustTime", typeof(DateTime));
for (int i = 0; i < 10; i++)
DT.Rows.Add(DateTime.Now, DateTime.Now, DateTime.Now);
this.dataGridView1.AutoGenerateColumns = false;
FormatColumns(this.dataGridView1);
this.dataGridView1.DataSource = DT;
}
private void FormatColumns(DataGridView DGW)
{
DataGridViewCellStyle cStyle = new DataGridViewCellStyle();
// Second column will be formatted as DateOnly
cStyle.Format = "d";
cStyle.NullValue = null;
this.dataGridView1.Columns[1].DefaultCellStyle = cStyle;
// Third column will be formatted as TimeOnly
cStyle = new DataGridViewCellStyle();
cStyle.Format = "T";
cStyle.NullValue = null;
this.dataGridView1.Columns[2].DefaultCellStyle = cStyle;
}
Hope this helps,
Palli