C# DataGridView 列的日期时间格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10644788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# DataGridView date time formatting of a column
提问by user1063108
I have datagridview which fills data from database, there are columns where I have date and time in them "MMddyyyy" and "hhmmss" format, what I want to do is when the datagridview loads, I want to change this format to some other format say, dd-MM-yy for date and for time hh-mm-ss. I was wondering if some one can guide me how to do it. I have not been able to do this by gridview.columns[x].defaultcellstyle.format="dd-MM-yy" with the above I get no error but nothing is changed on the gridview ...
我有 datagridview 填充数据库中的数据,有些列中我有日期和时间“MMddyyyy”和“hhmmss”格式,我想要做的是当 datagridview 加载时,我想将此格式更改为其他格式例如,dd-MM-yy 用于日期和时间 hh-mm-ss。我想知道是否有人可以指导我如何去做。我无法通过 gridview.columns[x].defaultcellstyle.format="dd-MM-yy" 做到这一点,上面我没有错误,但 gridview 上没有任何变化......
Thanks
谢谢
Note:I dont have the option to change the column length in the database as well..:-( there are no syntax problems
注意:我也没有更改数据库中列长度的选项..:-( 没有语法问题
采纳答案by web_bod
Microsoft suggest you intercept the CellFormatting event (where DATED is the column you want to reformat):
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;
}
}
}
回答by Lev Z
The sintax in DataGridView formating is a little different then in DateTime, but you can get the same result. In my example i have a Time collumn, that by default shows HH:mm:ss and I want to show only hours and minutes:
DataGridView 格式中的语法与 DateTime 中的语法略有不同,但您可以获得相同的结果。在我的示例中,我有一个时间列,默认情况下显示 HH:mm:ss,我只想显示小时和分钟:
yourDataGridView.Columns["Time"].DefaultCellStyle.Format = @"hh\:mm";

