我有从数据库中填充数据的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;
}
}
}
关于C# DataGridView 列的日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10644788/