How to export data from data grid view to pdf in vb - vb.net

I had to delete the previous question to re-evaluate my code properly. The last time I tried to print but it got confusing for me, So I did more research on how to export to pdf and wrote the code for it. When I run the program, I was able to save the pdf as it prompted me but after saving the file, the error popped up and read as follows:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Windows.Forms.DataGridViewCell.Value.get returned Nothing.
This is my code for the export button:
Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
SaveFileDialog1.ShowDialog()
If SaveFileDialog1.FileName = "" Then
MsgBox("enter filename to create pdf", vbExclamation)
Else
ExportDataToPDFTable
MsgBox("PDF file successfully created!", vbInformation)
End If
End Sub
Private Sub ExportDataToPDFTable()
Dim paragraph As New Paragraph
Dim doc As New Document(iTextSharp.text.PageSize.A4, 40, 40, 40, 10)
Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(SaveFileDialog1.FileName + ".pdf", FileMode.Create))
Dim font12Bold As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK)
Dim font12Normal As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8.0F, iTextSharp.text.Font.NORMAL, BaseColor.BLACK)
doc.Open()
Dim PdfTable As New PdfPTable(9)
PdfTable.TotalWidth = 490.0F
PdfTable.LockedWidth = True
Dim widths As Single() = New Single() {0.3F, 1.0F, 2.0F, 1.0F, 1.0F, 0.5F, 1.0F, 1.0F, 1.0F}
PdfTable.SetWidths(widths)
PdfTable.HorizontalAlignment = 1
PdfTable.SpacingBefore = 2.0F
Dim PdfCell As PdfPCell = Nothing
PdfCell = New PdfPCell(New Phrase(New Chunk("id", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Center
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("date", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Center
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("brand", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("size", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("selling unit price", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("cost unit price", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("Quantity", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("total selling price", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("total cost price", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
PdfCell = New PdfPCell(New Phrase(New Chunk("profit", font12Bold)))
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
PdfTable.AddCell(PdfCell)
Dim dt As DataTable = getDataTable()
If dt IsNot Nothing Then
For rows As Integer = 0 To dt.Rows.Count - 1
For columns As Integer = 0 To dt.Columns.Count - 1
PdfCell = New PdfPCell(New Phrase(dt.Rows(rows)(columns).ToString, font12Normal))
If columns = 4 Or columns = 6 Then
PdfCell.HorizontalAlignment = HorizontalAlignment.Right
Else
If columns = 0 Or columns = 5 Then
PdfCell.HorizontalAlignment = HorizontalAlignment.Center
Else
PdfCell.HorizontalAlignment = HorizontalAlignment.Left
End If
End If
Next
Next
doc.Add(PdfTable)
End If
doc.Close()
End Sub
Private Function getDataTable() As DataTable
Dim DataTable As New DataTable("MyDataTable")
' Dim dataColumn1 As New DataColumn(DataGridView1.Columns(0).HeaderText.ToString, GetType(String))
Dim dataColumn2 As New DataColumn(DataGridView1.Columns(2).HeaderText.ToString, GetType(String))
Dim dataColumn3 As New DataColumn(DataGridView1.Columns(3).HeaderText.ToString, GetType(String))
Dim dataColumn4 As New DataColumn(DataGridView1.Columns(4).HeaderText.ToString, GetType(String))
Dim dataColumn5 As New DataColumn(DataGridView1.Columns(5).HeaderText.ToString, GetType(String))
Dim dataColumn6 As New DataColumn(DataGridView1.Columns(6).HeaderText.ToString, GetType(String))
Dim dataColumn7 As New DataColumn(DataGridView1.Columns(7).HeaderText.ToString, GetType(String))
Dim dataColumn8 As New DataColumn(DataGridView1.Columns(8).HeaderText.ToString, GetType(String))
Dim dataColumn9 As New DataColumn(DataGridView1.Columns(9).HeaderText.ToString, GetType(String))
' Dim dataColumn10 As New DataColumn(DataGridView1.Columns(10).HeaderText.ToString, GetType(String))
' DataTable.Columns.Add(dataColumn1)
DataTable.Columns.Add(dataColumn2)
DataTable.Columns.Add(dataColumn3)
DataTable.Columns.Add(dataColumn4)
DataTable.Columns.Add(dataColumn5)
DataTable.Columns.Add(dataColumn6)
DataTable.Columns.Add(dataColumn7)
DataTable.Columns.Add(dataColumn8)
DataTable.Columns.Add(dataColumn9)
' DataTable.Columns.Add(dataColumn10)
Dim dataRow As DataRow
For i As Integer = 0 To DataGridView1.Rows.Count - 1
dataRow = DataTable.NewRow
' dataRow(DataGridView1.Columns(0).HeaderText.ToString) = DataGridView1.Rows(i).Cells(0).Value.ToString
dataRow(DataGridView1.Columns(2).HeaderText.ToString) = DataGridView1.Rows(i).Cells(2).Value.ToString
dataRow(DataGridView1.Columns(3).HeaderText.ToString) = DataGridView1.Rows(i).Cells(3).Value.ToString
dataRow(DataGridView1.Columns(4).HeaderText.ToString) = DataGridView1.Rows(i).Cells(4).Value.ToString
dataRow(DataGridView1.Columns(5).HeaderText.ToString) = DataGridView1.Rows(i).Cells(5).Value.ToString
dataRow(DataGridView1.Columns(6).HeaderText.ToString) = DataGridView1.Rows(i).Cells(6).Value.ToString
dataRow(DataGridView1.Columns(7).HeaderText.ToString) = DataGridView1.Rows(i).Cells(7).Value.ToString
dataRow(DataGridView1.Columns(8).HeaderText.ToString) = DataGridView1.Rows(i).Cells(8).Value.ToString
dataRow(DataGridView1.Columns(9).HeaderText.ToString) = DataGridView1.Rows(i).Cells(9).Value.ToString
' dataRow(DataGridView1.Columns(10).HeaderText.ToString) = DataGridView1.Rows(i).Cells(10).Value.ToString
Next
DataTable.AcceptChanges()
Return DataTable
End Function
With my IMPORTS:
Imports iTextSharp
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports System.IO
The query for retrieving data from the data grid view works fine, but I want the retrieved data from DGV to be exported to pdf once I click the "save as PDF" button. My error is after saving the pdf file, it's where the error has popped up and when opening the pdf file the error says:
screenshot of the error: https://snipboard.io/VF9RKQ.jpg from Adobe PDF
Screenshot of the DGV data after retrieved: https://snipboard.io/r627jz.jpg
I don't know where I went wrong. Why I'm not able to see DGV data on PDF? Did I miss something?

first of all, before doing DataGridView1.Rows(i).Cells(x).Value.ToString you must ensure DataGridView1.Rows(i).Cells(x).Value is not empty :
in getDataTable() replace lines
dataRow(DataGridView1.Columns(x).HeaderText.ToString) = DataGridView1.Rows(i).Cells(x).Value.ToString
by
'note : I simplified 'dataRow(DataGridView1.Columns(x).HeaderText.ToString)'
dataRow(x) = IIF(DataGridView1.Rows(i).Cells(x).Value is nothing, "", DataGridView1.Rows(i).Cells(x).Value.ToString)
IFF statement works like that :
IFF(condition, result if condition is true, result if false) so if cell is empty, datarow will be filled with "".
update : to track errors add try/catch and breakpoint
Try
dataRow(2) = IIF(DataGridView1.Rows(i).Cells(2).Value is nothing, "", DataGridView1.Rows(i).Cells(2).Value.ToString)
dataRow(3) = IIF(DataGridView1.Rows(i).Cells(3).Value is nothing, "", DataGridView1.Rows(i).Cells(3).Value.ToString)
dataRow(4) = IIF(DataGridView1.Rows(i).Cells(4).Value is nothing, "", DataGridView1.Rows(i).Cells(4).Value.ToString)
dataRow(5) = IIF(DataGridView1.Rows(i).Cells(5).Value is nothing, "", DataGridView1.Rows(i).Cells(5).Value.ToString)
dataRow(6) = IIF(DataGridView1.Rows(i).Cells(6).Value is nothing, "", DataGridView1.Rows(i).Cells(6).Value.ToString)
dataRow(7) = IIF(DataGridView1.Rows(i).Cells(7).Value is nothing, "", DataGridView1.Rows(i).Cells(7).Value.ToString)
dataRow(8) = IIF(DataGridView1.Rows(i).Cells(8).Value is nothing, "", DataGridView1.Rows(i).Cells(8).Value.ToString)
dataRow(9) = IIF(DataGridView1.Rows(i).Cells(9).Value is nothing, "", DataGridView1.Rows(i).Cells(9).Value.ToString)
Catch ex As Exception 'put break point here and look at ex value
End Try

Related

editing PDF to add page number | VB.net

I am looking to modify the pdf to add the page number and I cannot find why the variable "cb" is empty.
you can see error on the screen below
Error on the screen : "Object reference not set to an instance of an object"
I just found how to edit pdf and add pages number, here is my code for those who need it.
I copy a file, I count the number of pages, in a while loop I display the number of pages (1/3) then I import the page on which I wanted to add the number of pages.
Public Sub ModifPDF(ByVal annee As Integer, ByVal mois As Integer, ByVal nomFichier As String, ByVal sourceFileList As String)
Dim Col1 As PdfPCell
Dim Col2 As PdfPCell
Dim Font1 As New Font(FontFactory.GetFont(FontFactory.HELVETICA, 1, iTextSharp.text.Font.NORMAL))
Dim Font8 As New Font(FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.NORMAL))
Dim Vide As PdfPCell = New PdfPCell(New Phrase("")) With {
.Border = 0
}
Dim reader As New PdfReader(sourceFileList)
Dim sourceFilePageCount As Integer = reader.NumberOfPages
Dim doc As New Document(reader.GetPageSizeWithRotation(1))
My.Computer.FileSystem.CopyFile(sourceFileList, "C:\test")
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream("C:\test", FileMode.Open, FileAccess.Write))
doc.Open()
Dim contentByte As PdfContentByte = writer.DirectContent
Dim pageIndex As Integer = 0
While pageIndex < sourceFilePageCount
pageIndex = pageIndex + 1
doc.SetPageSize(reader.GetPageSize(pageIndex))
Dim TableNota As PdfPTable = New PdfPTable(2)
Dim widthsNota As Single() = New Single() {19.7F, 1.5F}
TableNota.WidthPercentage = 97
TableNota.SetWidths(widthsNota)
Col1 = New PdfPCell(New Phrase(" ", Font8)) With {
.Border = 0
}
TableNota.AddCell(Col1)
Col2 = New PdfPCell(New Phrase("page " & pageIndex & "/" & sourceFilePageCount & "", Font8)) With {
.Border = 0
}
TableNota.AddCell(Col2)
TableNota.AddCell(Vide)
doc.Add(TableNota)
Dim page = writer.GetImportedPage(reader, pageIndex)
Dim rotation = reader.GetPageRotation(pageIndex)
If rotation.Equals(90) Then
contentByte.AddTemplate(page, 0, -0.1F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(pageIndex).Height)
Else
contentByte.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0)
End If
doc.NewPage()
End While
doc.Close()
End Sub

How do i handle a multiple null image values from Microsoft SQL Server database with vb.net code

I was hoping someone could point me in the right direction with my current code. I'm getting an error while opening my program:
Data is Null. This method or property cannot be called on null values.
I put an else statement for btn.backgroundimage but still get that error.
Here is what my code looks like:
Sub FillItems()
Try
con = New SqlConnection(cs)
con.Open()
Dim PictureCol As Integer = 1 ' the column # of the BLOB field
Dim cmdText1 As String = "SELECT RTRIM(ProductName),Image from Temp_Stock_Company INNER JOIN Product ON Product.PID=Temp_Stock_Company.ProductID where ShowPOS='Yes'"
cmd = New SqlCommand(cmdText1)
cmd.Connection = con
cmd.CommandTimeout = 0
rdr = cmd.ExecuteReader()
flpItems.Controls.Clear()
Do While (rdr.Read())
'Dim btn As New Button
'btn.Text = rdr.GetValue(0)
'btn.TextAlign = ContentAlignment.MiddleCenter
'btn.BackColor = Color.SteelBlue
'btn.ForeColor = Color.White
'btn.FlatStyle = FlatStyle.Popup
'btn.Width = 125
'btn.Height = 60
'btn.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
'UserButtons.Add(btn)
'flpItems.Controls.Add(btn)
Dim b(rdr.GetBytes(PictureCol, 0, Nothing, 0, Integer.MaxValue) - 1) As Byte
rdr.GetBytes(PictureCol, 0, b, 0, b.Length)
Dim ms As New System.IO.MemoryStream(b)
Dim Dflp As New FlowLayoutPanel
Dflp.Size = New System.Drawing.Size(197, 197)
Dflp.BackColor = Color.Black
Dflp.BorderStyle = BorderStyle.None
Dflp.FlowDirection = FlowDirection.TopDown
Dim btn As New Button
Dim btnX As New Button
btn.Text = rdr.GetValue(0)
btn.Width = 197
btn.Height = 197
If DBNull.Value.Equals(rdr(1)) = False Then
btn.BackgroundImage = Image.FromStream(ms)
btn.BackgroundImageLayout = ImageLayout.Stretch
Else
btn.BackgroundImage = My.Resources._12
btn.BackgroundImageLayout = ImageLayout.Stretch
End If
btn.FlatStyle = FlatStyle.Flat
btn.FlatAppearance.BorderSize = 0
btn.Text = rdr.GetValue(0)
btn.Font = New System.Drawing.Font("Segoe UI Semibold", 1.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
btn.TextAlign = System.Drawing.ContentAlignment.BottomCenter
btn.ForeColor = System.Drawing.Color.Black
btnX.Text = rdr.GetValue(0)
btnX.FlatStyle = FlatStyle.Flat
btnX.Width = 0
btnX.Height = 0
btnX.FlatAppearance.BorderSize = 0
btnX.Text = rdr.GetValue(0)
btnX.Font = New System.Drawing.Font("Segoe UI Semibold", 8.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
btnX.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
btnX.ForeColor = Color.White
btnX.BackColor = Color.SteelBlue
UserButtons.Add(btn)
UserButtons.Add(btnX)
Dflp.Controls.Add(btn)
Dflp.Controls.Add(btnX)
flpItems.Controls.Add(Dflp)
AddHandler btn.Click, AddressOf Me.btnItems_Click
AddHandler btnX.Click, AddressOf Me.btnItems_Click
Loop
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
End Try
End Sub
You do not want to hold the connection open while you update the user interface so I have used a DataTable which will hold your data after the connection is closed and disposed. Using...End Using blocks will close and dispose your database objects. Any class in the framework that shows you a .Dispose method should be enclosed in Using blocks. This includes streams.
Load the DataTable. Check for DBNull and only then get your byte array.
I used AdventureWorks (a sample database available from Microsoft) to test.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.Adventure),
cmd As New SqlCommand("Select Top 10 ProductPhotoID, ThumbNailPhoto From Production.ProductPhoto;", cn)
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
For Each row As DataRow In dt.Rows
Dim btn As New Button
If Not IsDBNull(row(1)) Then
Dim b() As Byte = DirectCast(row(1), Byte())
Using ms As New System.IO.MemoryStream(b)
btn.BackgroundImage = Image.FromStream(ms)
End Using
Else
btn.BackgroundImage = Image.FromFile("C:\Users\***\Desktop\Graphics\TreeFrog.jpg")
End If
btn.BackgroundImageLayout = ImageLayout.Stretch
btn.Width = 50
btn.Height = 50
FlowLayoutPanel1.Controls.Add(btn)
Next
End Sub

Error while trying to export DataGridView as pdf

I'm trying to export a populated datagridview with the following code:
Imports System.Data.OleDb
Imports Microsoft.Office.Interop.Excel
Imports System.Drawing
Imports DGVPrinterHelper
Imports iTextSharp
Imports iTextSharp.text.pdf
Imports iTextSharp.text
Imports System.Data.Odbc
Imports System.IO
Private Sub Export_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
SaveFileDialog1.ShowDialog()
If SaveFileDialog1.FileName = "" Then
MsgBox("Enter Filename to create PDF")
Exit Sub
Else
ExportDataToPDFTable()
MsgBox("PDF Created Successfully")
End If
End Sub
Private Function GetDataTable() As DataTable
Dim dataTable As New Data.DataTable("MyDataTable")
'Create another DataColumn Name
For column As Integer = 1 To DataGridView1.ColumnCount - 1
Dim dataColumn_1 As New DataColumn(DataGridView1.Columns(column).HeaderText.ToString(), GetType(String))
dataTable.Columns.Add(dataColumn_1)
'Now Add some row to newly created dataTable
Dim dataRow As DataRow
For i As Integer = 0 To DataGridView1.Rows.Count - 1
dataRow = dataTable.NewRow()
' Important you have create New row
dataRow(DataGridView1.Columns(column).HeaderText.ToString()) = DataGridView1.Rows(i).Cells(column).Value.ToString()
dataTable.Rows.Add(dataRow)
Next i
Next column
dataTable.AcceptChanges()
Return dataTable
End Function
Private Sub ExportDataToPDFTable()
Dim paragraph As New Paragraph
Dim doc As New Document(iTextSharp.text.PageSize.A4, 40, 40, 40, 10)
Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(SaveFileDialog1.FileName + ".pdf", FileMode.Create))
doc.Open()
Dim font12BoldRed As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12.0F, iTextSharp.text.Font.UNDERLINE Or iTextSharp.text.Font.BOLDITALIC, BaseColor.RED)
Dim font12Bold As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK)
Dim font12Normal As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12.0F, iTextSharp.text.Font.NORMAL, BaseColor.BLACK)
Dim p1 As New Phrase
p1 = New Phrase(New Chunk("PDF From Datagridview Data", font12BoldRed))
doc.Add(p1)
'Create instance of the pdf table and set the number of column in that table
Dim PdfTable As New PdfPTable(5)
PdfTable.TotalWidth = 490.0F
'fix the absolute width of the table
PdfTable.LockedWidth = True
'relative col widths in proportions - 1,4,1,1 and 1
Dim widths As Single() = New Single() {1.0F, 4.0F, 1.0F, 1.0F, 1.0F}
PdfTable.SetWidths(widths)
PdfTable.HorizontalAlignment = 1 ' 0 --> Left, 1 --> Center, 2 --> Right
PdfTable.SpacingBefore = 2.0F
'pdfCell Decleration
Dim PdfPCell As PdfPCell = Nothing
'Assigning values to each cell as phrases
PdfPCell = New PdfPCell(New Phrase(New Chunk("Taxcode", font12Bold)))
'Alignment of phrase in the pdfcell
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
'Add pdfcell in pdftable
PdfTable.AddCell(PdfPCell)
PdfPCell = New PdfPCell(New Phrase(New Chunk("Tax Name", font12Bold)))
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
PdfTable.AddCell(PdfPCell)
PdfPCell = New PdfPCell(New Phrase(New Chunk("Cess Tax", font12Bold)))
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
PdfTable.AddCell(PdfPCell)
PdfPCell = New PdfPCell(New Phrase(New Chunk("Sales Tax", font12Bold)))
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
PdfTable.AddCell(PdfPCell)
PdfPCell = New PdfPCell(New Phrase(New Chunk("Other Tax", font12Bold)))
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
PdfTable.AddCell(PdfPCell)
Dim dt As DataTable = GetDataTable()
If dt IsNot Nothing Then
'Now add the data from datatable to pdf table
For rows As Integer = 0 To dt.Rows.Count - 1
For column As Integer = 0 To dt.Columns.Count - 1
PdfPCell = New PdfPCell(New Phrase(dt.Rows(rows)(column).ToString(), font12Normal))
If column = 0 Or column = 1 Then
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT
Else
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT
End If
PdfTable.AddCell(PdfPCell)
Next
Next
'Adding pdftable to the pdfdocument
doc.Add(PdfTable)
End If
doc.Close()
End Sub
When I run the program a click the button it prompts me with the SaveFileDialog, but once I click save I get the error "Unable to cast object of type 'System.Data.DataTable' to type 'Microsoft.Office.Interop.Excel.DataTable'." at the "Return dataTable" line in the Private Function GetDataTable(). Can anyone help me resolve this issue? And please feel free to point out other errors with my code (if there are any)

Getting OutOfRange exception when trying to insert values from datagridview into PDFtable

I have a datagridview that I'm trying to export in pdf format. I downloaded and implemented a datagridviewtopdf class, but I needed to modify it to dynamically create the necessary columns (the column count will range from 1-12 for months in a year). I also needed to include an extra column to put the row header text for each row in my datagridview. I have the code, which I will include below. I keep getting an OutOfRange exception at the line that I've starred. Any idea how to fix this and create the pdf to resemble my datagridview table?
Edited to also include screenshots of datagridview. Datagridview will have up to 65 rows and up to 12 columns (not including rowheaders or columnheaders
Private Function GetDataTable() As System.Data.DataTable
Dim dataTable As New Data.DataTable("MyDataTable")
'Create another DataColumn Name
For column As Integer = 1 To DataGridView1.ColumnCount - 1
Dim dataColumn_1 As New DataColumn(DataGridView1.Columns(column).HeaderText.ToString(), GetType(String))
dataTable.Columns.Add(dataColumn_1)
'Now Add some row to newly created dataTable
Dim dataRow As DataRow
For i As Integer = 0 To DataGridView1.Rows.Count - 1
dataRow = dataTable.NewRow()
' Important you have create New row
dataRow(DataGridView1.Columns(column).HeaderText.ToString()) = DataGridView1.Rows(i).Cells(column).Value.ToString()
dataTable.Rows.Add(dataRow)
Next i
Next column
dataTable.AcceptChanges()
Return dataTable
End Function
Private Sub ExportDataToPDFTable()
Dim paragraph As New Paragraph
Dim doc As New Document(iTextSharp.text.PageSize.A4, 40, 40, 40, 10)
Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(SaveFileDialog1.FileName + ".pdf", FileMode.Create))
doc.Open()
Dim font12BoldRed As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12.0F, iTextSharp.text.Font.UNDERLINE Or iTextSharp.text.Font.BOLDITALIC, BaseColor.RED)
Dim font12Bold As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK)
Dim font12Normal As New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12.0F, iTextSharp.text.Font.NORMAL, BaseColor.BLACK)
Dim p1 As New Phrase
p1 = New Phrase(New Chunk("PDF From Datagridview Data", font12BoldRed))
doc.Add(p1)
'Create instance of the pdf table and set the number of column in that table
Dim PdfTable As New PdfPTable(DataGridView1.ColumnCount + 1)
PdfTable.TotalWidth = 490.0F
'fix the absolute width of the table
PdfTable.LockedWidth = True
'relative col widths in proportions - 1,4,1,1 and 1
'Dim widths As Single() = New Single() {1.0F, 1.0F, 1.0F, 1.0F, 1.0F}
' PdfTable.SetWidths(widths)
PdfTable.HorizontalAlignment = 1 ' 0 --> Left, 1 --> Center, 2 --> Right
PdfTable.SpacingBefore = 2.0F
'pdfCell Decleration
Dim PdfPCell As PdfPCell = Nothing
'Assigning values to each cell as phrases
For column As Integer = 0 To (DataGridView1.ColumnCount - 1)
If column = 0 Then
For row As Integer = 0 To (DataGridView1.RowCount - 1)
'Getting out of range exception below for row
PdfPCell = New PdfPCell(New Phrase(New Chunk(DataGridView1.Rows(row).HeaderCell.ToString, font12Bold)))
'Add pdfcell in pdftable
PdfTable.AddCell(PdfPCell)
Next row
Else
PdfPCell = New PdfPCell(New Phrase(New Chunk(DataGridView1.Columns(column).HeaderText, font12Bold)))
'Alignment of phrase in the pdfcell
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER
'Add pdfcell in pdftable
PdfTable.AddCell(PdfPCell)
End If
Next column
Dim dt = GetDataTable()
If dt IsNot Nothing Then
'Now add the data from datatable to pdf table
For rows As Integer = 0 To dt.Rows.Count - 1
For column As Integer = 0 To dt.Columns.Count - 1
PdfPCell = New PdfPCell(New Phrase(dt.Rows(rows)(column).ToString(), font12Normal))
If column = 0 Or column = 1 Then
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT
Else
PdfPCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT
End If
PdfTable.AddCell(PdfPCell)
Next
Next
'Adding pdftable to the pdfdocument
doc.Add(PdfTable)
End If
doc.Close()
End Sub
Change:
For column As Integer = 1 To DataGridView1.ColumnCount + 1
For row As Integer = 1 To DataGridView1.RowCount
To:
For column As Integer = 0 To (DataGridView1.ColumnCount - 1)
For row As Integer = 0 To (DataGridView1.RowCount -1)
Remember: It's zero-base indexing.
Example:
Dim dtColumn As DataColumn
Dim dtRow As DataRow
For column As Integer = 0 To (Me.DataGridView1.ColumnCount - 1)
dtColumn = dt.Columns.Item(Me.DataGridView1.Columns(column).DataPropertyName)
For row As Integer = 0 To (DataGridView1.RowCount - 1)
dtRow = DirectCast(Me.DataGridView1.Rows(row).DataBoundItem, DataRowView).Row
'Replace this:
'PdfPCell = New PdfPCell(New Phrase(dt.Rows(rows)(column).ToString(), font12Normal))
'With this:
PdfPCell = New PdfPCell(New Phrase(row.Item(column).ToString(), font12Normal))
Next
Next

Printing images in Crystal Reports from VB.Net

I want to print an image in Crystal Reports. I got some code from the web but the image doesn't show; only the text "ok" on the first column was shown.
Any suggestions would greatly appreciated.
Thanks in advance
Here is my code
Dim myRpt As New ImageReport
Dim txtHeader As CrystalDecisions.CrystalReports.Engine.TextObject = myRpt.Section2.ReportObjects("txtHeader")
txtHeader.Text = "IMAGE AND TEXT"
Dim txtDateNow As CrystalDecisions.CrystalReports.Engine.TextObject = myRpt.Section2.ReportObjects("txtDateNow")
txtDateNow.Text = Format(Now(), "MMMM d, yyyy")
Dim row As DataRow = Nothing
Dim DS As New DataSet
'ADD A TABLE TO THE DATASET
DS.Tables.Add("rp_recipe_cr_image_report")
'ADD THE COLUMNS TO THE TABLE
With DS.Tables(0).Columns
.Add("others_t1", Type.GetType("System.String"))
.Add("image", Type.GetType("System.Byte[]"))
End With
Dim fs As New FileStream("D:\asianporkroll.Jpg", FileMode.Open)
Dim br As New BinaryReader(fs)
Dim lBImageByte As Byte()
lBImageByte = New Byte(fs.Length + 1) {}
lBImageByte = br.ReadBytes(Convert.ToInt32(fs.Length))
row = DS.Tables(0).NewRow
row(0) = "ok"
row(1) = lBImageByte
DS.Tables(0).Rows.Add(row)
br.Close()
fs.Close()
myRpt.SetDataSource(DS)
CrystalReportViewer1.ReportSource = myRpt
CrystalReportViewer1.Refresh()
'DISPOSE OF THE DATASET
DS.Dispose()
DS = Nothing