0

I have a datagridview with a date column. I'm making a printable report of that datagridview. For that I'm using this line of code:

e.Graphics.DrawString(dataGridView1.Rows[i].Cells["Date"].FormattedValue.ToString(), new Font("Arial", 10, FontStyle.Regular), Brushes.Black, x, 140 + height);

This gives me an output on the report in this format 11/09/2021 10:15 I'd like to have the date on the report, without the time: 11/09/2021

So far I've tried this:

  • e.Graphics.DrawString(dataGridView1.Rows[i].Cells["Date"].FormattedValue.ToString("dd/MM/yyyy"), new Font("Arial", 10, FontStyle.Regular), Brushes.Black, x, 140 + height);: this gives me the following error: 'No overload for method 'ToString' takes 1 argument'
  • string date = dataGridView1.Rows[i].Cells["Date"].FormattedValue.ToString(); newdate = date.Substring(0, 9); this gives me the following error when rendering the report: 'System.ArgumentOutOfRangeException: 'index and length must refer to a location within the string. parameter name'

At the moment, I'm out of inspiration..... Any suggestions?

Kind regards, Christophe

Christophe
  • 39
  • 12
  • What is the underlying data source for the grid view? – ProgrammingLlama Mar 10 '21 at 08:10
  • 2
    You need to format the Value of the cell. FormattedValue is already a string – Steve Mar 10 '21 at 08:13
  • @Berk converting the output of _void Graphics.DrawString_ to a DateTime? – Steve Mar 10 '21 at 08:18
  • 1
    @Steve yes otherwise you can't use `ToString("dd/MM/yyyy")` Edit 1: I meant to convert value sorry. It should be `Convert.ToDateTime(dataGridView1.Rows[i].Cells["Date"]).ToString("dd/MM/yyyy")` – Berk Mar 10 '21 at 08:20
  • @John the underlying data source is a database with date column. The type is timestamp and the format is 2021-01-15 08:54:50 – Christophe Mar 10 '21 at 08:24
  • There are a number of different approaches to formatting a `DateTime` value in a `DataGridView` object. None of them involve trying to call `ToString()` on the `FormattedValue` property's value, because `FormattedValue` returns a `string` reference, not a `DateTime` value. – Peter Duniho Mar 10 '21 at 08:29

1 Answers1

1

You should convert to a datetime the property Value of your DataGridViewRow. This is typed as an object so you need a conversion. At that point you can use the overload of ToString available for the DateTime type that accepts the output format required.

For clarity I put the code in separate lines.

 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);
Steve
  • 213,761
  • 22
  • 232
  • 286