C# 如何在DataGridView中格式化DateTime列?

C# 如何在DataGridView中格式化DateTime列?,c#,winforms,data-binding,datetime,datagridview,C#,Winforms,Data Binding,Datetime,Datagridview,我使用带有对象数据绑定的DataGridView来显示有关系统中记录实体的信息,这些信息通过SOAP从远程服务检索。 其中一列称为“Last action”,表示实体最后一次记录消息的时间。它是一个System.DateTime值。当我阅读SOAP响应(下面的示例)时,时间戳显然包含了所有信息,最多是第二个分数 <LoggingEntity> <host>marty86ce</host> <process>10148</process>

我使用带有对象数据绑定的DataGridView来显示有关系统中记录实体的信息,这些信息通过SOAP从远程服务检索。 其中一列称为“Last action”,表示实体最后一次记录消息的时间。它是一个
System.DateTime
值。当我阅读SOAP响应(下面的示例)时,时间戳显然包含了所有信息,最多是第二个分数

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

先谢谢你


Logbus ng开源项目(FFDAGui程序)上的完整解决方案代码。

使用属性或设置它

您可以设置所需的格式:

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

您可以在aspx中设置格式,只需在边界字段中添加属性“DateFormatString”

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

我使用了这些代码,希望能有所帮助

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

如果是windows窗体Datagrid,则可以使用以下代码格式化列的日期时间

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

除此之外,如果您需要AM/PM格式的datetime,您可以使用以下代码

dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy hh:mm:ss tt";
由Microsoft发布于:

这将根据人员的位置设置设置日期的格式


这是Microsoft更大的数据集的一部分。

dd/MM/yyyy
将日期格式化为
dd-MM-yyyy
。使用
dd'/'MM'/'yyyyy
将日期格式化为
dd/MM/yyyy
yourColumn.DefaultCellStyle=new DataGridViewCellStyle{format=“dd'/'MM'/'yyyyy hh:MM:ss”}dataGridViewCellStyle
是什么?您可以添加一些解释吗?如果您是手动填充行,您需要将日期时间转换为字符串。ToString(“d”)指定DateTime ToString方法中的仅日期格式。在
System.Windows.Forms.DataGridViewCell
中没有此类DateFormatString属性。如何在WPF中执行此操作?请您解释为什么以及如何解决此问题?在数据绑定列时应设置格式字符串。
dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy hh:mm:ss tt";
dataGrid.Columns[2].DefaultCellStyle.Format = "d"; // Short date
string stringtodate = ((DateTime)row.Cells[4].Value).ToString("MM-dd-yyyy");
textBox9.Text = stringtodate;