C# 在C中将日期字符串从datagridview格式化为dd/MM/yyyy#

C# 在C中将日期字符串从datagridview格式化为dd/MM/yyyy#,c#,date,datagridview,C#,Date,Datagridview,我有一个带有日期列的datagridview。我正在制作datagridview的可打印报告。 为此,我使用以下代码行: e.Graphics.DrawString(dataGridView1.Rows[i].Cells["Date"].FormattedValue.ToString(), new Font("Arial", 10, FontStyle.Regular), Brushes.Black, x, 140 + height); 这给了我一个报告

我有一个带有日期列的datagridview。我正在制作datagridview的可打印报告。 为此,我使用以下代码行:

e.Graphics.DrawString(dataGridView1.Rows[i].Cells["Date"].FormattedValue.ToString(), new Font("Arial", 10, FontStyle.Regular), Brushes.Black, x, 140 + height);
这给了我一个报告的输出,格式为11/09/2021 10:15 我想知道报告上的日期,没有时间:2021年9月11日

到目前为止,我已经尝试过:

  • e.Graphics.DrawString(dataGridView1.Rows[i].单元格[“Date”].格式值.ToString(“dd/MM/yyyy”)、新字体(“Arial”、10、FontStyle.Regular)、画笔.Black、x、140+高度):这给了我以下错误:“方法“ToString”没有重载,只接受1个参数”
  • string date=dataGridView1.Rows[i]。单元格[“date”]。FormattedValue.ToString();newdate=date.Substring(0,9)这在呈现报告时给了我以下错误:“System.ArgumentOutOfRangeException:”索引和长度必须引用字符串中的位置。参数名'
目前,我没有灵感。。。。。 有什么建议吗


您好,Christophe

您应该将DataGridViewRow的属性值转换为datetime。这是作为对象键入的,因此需要进行转换。此时,可以对接受所需输出格式的DateTime类型使用ToString重载

为了清楚起见,我将代码放在单独的行中

 DateTime dt = Convert.ToDateTime(dataGridView1.Rows[i].Cells["Date"].Value);
 string toOutput = dt.ToString("dd/MM/yyyy"); 
 e.Graphics.DrawString(toOuput, new Font("Arial", 10, FontStyle.Regular), Brushes.Black, x, 140 + height);

网格视图的底层数据源是什么?您需要格式化单元格的值。FormattedValue已经是一个string@Berk是否将void Graphics.DrawString的输出转换为日期时间?@Steve yes,否则您不能使用
ToString(“dd/MM/yyyy”)
Edit 1:对不起,我想转换值。它应该是
Convert.ToDateTime(dataGridView1.Rows[i].Cells[“Date”]).ToString(“dd/MM/yyyy”)
@John基础数据源是一个带有日期列的数据库。类型是timestamp,格式是2021-01-15 08:54:50太好了!解决了我的问题!谢谢