在 C# 中将日期字符串从 datagridview 格式化为 dd/MM/yyyy
Format date-string from datagridview to dd/MM/yyyy in C#
我有一个带有日期列的数据网格视图。我正在制作该数据网格视图的可打印报告。
为此,我正在使用这行代码:
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
我想要报告上的日期,没有时间:11/09/2021
到目前为止我试过这个:
e.Graphics.DrawString(dataGridView1.Rows[i].Cells["Date"].FormattedValue.ToString("dd/MM/yyyy"), new Font("Arial", 10, FontStyle.Regular), Brushes.Black, x, 140 + height);
:这给了我以下错误:'No overload for method 'ToString' takes 1 argument'
string date = dataGridView1.Rows[i].Cells["Date"].FormattedValue.ToString(); newdate = date.Substring(0, 9);
呈现报告时出现以下错误:'System.ArgumentOutOfRangeException: 'index and length must refer to a location within the string. parameter name'
此刻,我没有灵感了.....
有什么建议吗?
亲切的问候,克里斯托夫
您应该将 DataGridViewRow 的 属性 值转换为日期时间。这是类型为对象,因此您需要进行转换。此时,您可以使用可用于接受所需输出格式的 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);
我有一个带有日期列的数据网格视图。我正在制作该数据网格视图的可打印报告。 为此,我正在使用这行代码:
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 我想要报告上的日期,没有时间:11/09/2021
到目前为止我试过这个:
e.Graphics.DrawString(dataGridView1.Rows[i].Cells["Date"].FormattedValue.ToString("dd/MM/yyyy"), new Font("Arial", 10, FontStyle.Regular), Brushes.Black, x, 140 + height);
:这给了我以下错误:'No overload for method 'ToString' takes 1 argument'string date = dataGridView1.Rows[i].Cells["Date"].FormattedValue.ToString(); newdate = date.Substring(0, 9);
呈现报告时出现以下错误:'System.ArgumentOutOfRangeException: 'index and length must refer to a location within the string. parameter name'
此刻,我没有灵感了..... 有什么建议吗?
亲切的问候,克里斯托夫
您应该将 DataGridViewRow 的 属性 值转换为日期时间。这是类型为对象,因此您需要进行转换。此时,您可以使用可用于接受所需输出格式的 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);