0

My datagridview doesn't have the time in datePurchased column. But when I exported it to PDF, it already includes the time. I need only the date not the time. Below is the sample code

 //For exporting to pdf

      Private Sub ExportButton_Click(sender As Object, e As  EventArgs) Handles ExportButton.Click
  connection.Close()
  connection.Open()

  Dim pdfTable As New PdfPTable(ReportDataGridView.ColumnCount)
  pdfTable.DefaultCell.Padding = 1
  pdfTable.WidthPercentage = 100
  pdfTable.DefaultCell.HorizontalAlignment = Element. ALIGN_CENTER

  Dim ptable As New  Font(iTextSharp.text.Font.FontFamily.HELVETICA, 11, iTextSharp.text.Font.BOLD, BaseColor.BLACK)

    For Each column As DataGridViewColumn in ReportDataGridView.Columns
  Dim cell as new PdfPCell(New Phrase(New Chunk(column.HeaderText, ptable)))
  cell.HorizontalAlignment = Element.ALIGN_CENTER
  cell.FixedHeight = 30
  pdfTable.AddCell(cell)

  Next

    For Each row as DataGridViewRow In ReportDataGridView.Rows
  For each cell as DataGridViewCell In row.Cells
  pdfTable.AddCell(cell.Value.ToString)
  Next
  Next

 Dim folderpath As String = "C:\PDFs\"
 If Not Directory.Exists(folderpath) Then
      Directory.CreateDirectory(folderpath)
 End If

  Using sfd as New 
SaveFileDialog()
 sfd.ShowDialog()
 sfd.OverWritePrompt = True
 sfd.Title =" Save As"
 sfd.AddExtension = True
 sfd.DefaultExt = ".pdf"

  Using stream As New FileStream(sfd.FileName & ".pdf", 
   FileMode.Create)
  Dim pdfdoc As New 
  Document (PageSize.LETTER, 36.0F, 36.0F,36.0F,36.0F)
  PdfWriter.GetInstance(pdfdoc.stream)
  pdfdoc.Open()
  pdfdoc.Add(pdfTable)
  pdfdoc.Close()
  stream.Close()
  If File.Exists("path") Then
       File.AppendAllText("path", "contents")
   End If
  pdfdoc.Close()
  stream.Close()
  End Using

  End Using
  End Sub

If you would ask me what's the data type of DatePurchased, it is date. I used date not datetime. Please help!

Annie
  • 1
  • 1
  • A date and a time are related to the same concept - expressing a moment in the future/in history - the underlying type is DateTime and always has a date and a time. In your grid you only see the date part of the datetime, because that is all your grid textbox is formatting to show (it is showing MM/dd/yyyy or whatever) though the time component of the datetime still exists. You must apply the same formatting when you emit the value – Caius Jard May 28 '20 at 08:22

1 Answers1

0

You would have to detect dates and explicitly format without time, e.g.

For each cell as DataGridViewCell In row.Cells
    Dim cellValue = cell.Value

    pdfTable.AddCell(If(TypeOf cellValue Is Date,
                        CDate(cellValue).ToShortDateString(),
                        cellValue.ToString()))
Next
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46