如何在c#中导出txt时保持datagrid datetime字段格式化 [英] how to keep datagrid datetime field formating while exporting in txt in c#

查看:54
本文介绍了如何在c#中导出txt时保持datagrid datetime字段格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过以下代码导出txt文件中的datagrid字段值。在导出其工作正常时,仅在日期时间字段的格式化中,它有一些问题。

在datagrid字段中,日期时间格式为dd / MM / yyyy hh:mm:ss AM / PM,但在文本文件中导出后,其更改为dd / MM / yyyy hh:mm:ss。导出的txt文件中缺少AM / PM值。



请建议如何在导出的txt文件中保留所需的datagrid日期时间格式。



请参考我在导出选项中使用的给定代码。



TextWriter sw = new StreamWriter(@C: \\Export \\Export.txt);

int rowcount = dataGridView1.Rows.Count;

for(int i = 0; i< rowcount - 1; i ++)

{

sw.WriteLine(dataGridView1.Rows [i] .Cells [0] .Value.ToString()+|

+ dataGridView1.Rows [i] .Cells [1] .Value.ToString()+|

+ dataGridView1.Rows [i] .Cells [2] .Value .ToString()+|

+ dataGridView1.Rows [i] .Cells [3] .Value.ToString()+|

+ dataGridView1.Rows [i] .Cells [4] .Value.ToString()+|);







}

sw.Close();

MessageBox.Show(数据导出成功);

解决方案

如果使用标准的ToString实现(即在DateTime对象上没有参数,那么你得到的字符串取决于它运行的PC的本地设置。

您需要将值强制转换为DateTime(因为Value属性返回对象)并使用适当的格式字符串调用ToString:格式化日期时间以显示 - 格式字符串描述 [ ^ ]

I am exporting my datagrid field values in txt file through given below code. While exporting its working fine, only in formatting of datetime field, its have some issue.
In the datagrid fields, datetime formatting is "dd/MM/yyyy hh:mm:ss AM/PM", but after exporting in text file, its changed with "dd/MM/yyyy hh:mm:ss". "AM/ PM " value is missing in exported txt file.

Please suggest, how to keep required datagrid datetime format in exported txt file also.

please refer given code which i am using in my export option.

TextWriter sw = new StreamWriter(@"C:\\Export\\Export.txt");
int rowcount = dataGridView1.Rows.Count;
for (int i = 0; i < rowcount - 1; i++)
{
sw.WriteLine(dataGridView1.Rows[i].Cells[0].Value.ToString() + "|"
+ dataGridView1.Rows[i].Cells[1].Value.ToString() + "|"
+ dataGridView1.Rows[i].Cells[2].Value.ToString() + "|"
+ dataGridView1.Rows[i].Cells[3].Value.ToString() + "|"
+ dataGridView1.Rows[i].Cells[4].Value.ToString() + "|");



}
sw.Close();
MessageBox.Show("Data Exported Sucessfully");

解决方案

If you use the standard ToString implementation (i.e. with no parameters) on a DateTime object, then the string you get depends on the local settings for the PC it is being run on.
You need to cast the value to a DateTime (because the Value property returns an object) and call ToString with an appropriate format string: Formatting a DateTime for display - format string description[^]


这篇关于如何在c#中导出txt时保持datagrid datetime字段格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆