C#DataGridView列的日期时间格式

我有datagridview从数据库填充数据,有些列我在其中有日期和时间“MMddyyyy”和“hhmmss”格式,我想要做的是当datagridview加载时,我想将此格式更改为其他格式比如,dd-MM-yy的日期和时间hh-mm-ss。 我想知道是否有人可以指导我如何做到这一点。 我无法通过gridview.columns [x] .defaultcellstyle.format =“dd-MM-yy”用上面的方法做到这一点我没有得到任何错误但在gridview上没有任何改变…

谢谢

注意:我没有选项来更改数据库中的列长度.. :-(没有语法问题

Microsoft建议您拦截CellFormatting事件(其中DATED是您要重新格式化的列):

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { // If the column is the DATED column, check the // value. if (this.dataGridView1.Columns[e.ColumnIndex].Name == "DATED") { ShortFormDateFormat(e); } } private static void ShortFormDateFormat(DataGridViewCellFormattingEventArgs formatting) { if (formatting.Value != null) { try { DateTime theDate = DateTime.Parse(formatting.Value.ToString()); String dateString = theDate.ToString("dd-MM-yy"); formatting.Value = dateString; formatting.FormattingApplied = true; } catch (FormatException) { // Set to false in case there are other handlers interested trying to // format this DataGridViewCellFormattingEventArgs instance. formatting.FormattingApplied = false; } } } 

DataGridView格式化中的sintax与DateTime略有不同,但您可以得到相同的结果。 在我的例子中,我有一个Time collumn,默认显示HH:mm:ss,我想只显示小时和分钟:

  yourDataGridView.Columns["Time"].DefaultCellStyle.Format = @"hh\:mm";