2010-10-27 179 views
27

我正在使用DataGridView和对象数据绑定来显示有关系统中日志实体的信息,这些信息是通过SOAP从远程服务中检索的。 其中一列称为“Last action”,表示实体最后一次记录消息。这是一个System.DateTime值。当我读到SOAP响应(下面的例子)时,他的时间戳显然包含了所有的信息,直到第二部分。如何在DataGridView中格式化DateTime列?

<LoggingEntity> 
<host>marty86ce</host> 
<process>10148</process> 
<logger>http_core</logger> 
<appName>httpd</appName> 
<ffda>true</ffda> 
<lastAction>2010-10-27T12:00:19.5117509Z</lastAction> 
<lastHeartbeat>0001-01-01T00:00:00</lastHeartbeat> 
<channelId>em_9BA2A2B4D0B6E66</channelId> 
<ffdaChannelId>em_E7C8D1D4DE8EEB9</ffdaChannelId> 
</LoggingEntity> 

当我在表格中显示的话,我反而可以读取高达分钟 http://i.stack.imgur.com/dLYBz.png 我用下面的代码做数据绑定当我按下刷新按钮

public void RefreshEntities() 
{ 
    IEntityManagement management = EntityPlugin.GetProxy(); 
    LoggingEntity[] result = management.FindLoggingEntities(new TemplateQuery { ffdaSpecified = true, ffda = true }); //Remote invocation 

    Invoke(new MethodInvoker(delegate { gridEntities.DataSource = result; })); //THIS does the data binding from the array 

    Invoke(new MethodInvoker(delegate { btnRefresh.Enabled = true; })); 
} 

我想知道如何控制数据绑定值的列格式。我认为格式dd/MM/yyyy hh:mm来自我的系统设置。 如何以编程方式覆盖格式设置?

预先感谢您对Subversion(FFDAGui程序)

完整的解决方案代号为Logbus-ng的开源项目。

+0

如何在WPF中做到这一点? – 2017-02-17 06:19:23

回答

14

如果它是一个Windows窗体DataGrid,您可以使用下面的代码格式化日期时间为列

dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy HH:mm:ss"; 

编辑:

除此之外,如果你需要达上午/上午格式,你可以使用下面的代码

dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy hh:mm:ss tt"; 
+0

第一个例子中的“HH:MM:ss”不起作用,因为MM是月份而不是分钟。 – 2016-09-01 05:41:08

+0

更正。这是一个错字。谢谢@ManuelHoffmann – 2016-09-05 09:36:55

27

你可以设置你想要的格式:

dataGridViewCellStyle.Format = "dd/MM/yyyy"; 
this.date.DefaultCellStyle = dataGridViewCellStyle; 
// date being a System.Windows.Forms.DataGridViewTextBoxColumn 
+4

'dd/MM/yyyy'将日期格式设置为'dd-MM-yyyy'。使用'dd'/'MM'/'yyyy'将日期格式化为'dd/MM/yyyy' – TFischer 2014-05-16 17:52:53

+2

'yourColumn.DefaultCellStyle = new DataGridViewCellStyle {Format =“dd'/'MM'/'yyyy hh:mm:ss “};' – Appulus 2015-05-05 22:33:53

+0

不幸的是,它并没有改变我的任何事情。我的约会保持原样。看起来像我列中的日期被视为一个字符串,它使它不可形成。除了这一点,对日期有特殊要求,它们是真实的日期值? – C4u 2016-02-05 11:18:43

0

您可以在ASPX格式,只需在您的BoundField添加属性“DateFormatString”。

DataFormatString="{0:dd/MM/yyyy hh:mm:ss}" 
+0

'System.Windows.Forms.DataGridViewCell'中没有这样的DateFormatString属性 – 2016-12-29 13:17:54

0

我用这些代码,希望它可以帮助

dataGridView2.Rows[n].Cells[3].Value = item[2].ToString(); 
dataGridView2.Rows[n].Cells[3].Value = Convert.ToDateTime(item[2].ToString()).ToString("d"); 
+0

您可以添加一些解释吗? – 2016-06-05 13:06:17

+0

这是如果您手动填充行,并且您希望将DateTime转换为字符串。 ToString(“d”)从DateTime ToString方法指定仅日期格式。 – galamdring 2017-06-02 13:59:30