Click here to Skip to main content
15,896,606 members
Home / Discussions / Visual Basic
   

Visual Basic

 
AnswerRe: vb6 vidoes Pin
CHill6020-May-13 0:06
mveCHill6020-May-13 0:06 
QuestionVB.net 2010 form positioning Pin
athan_makubex19-May-13 9:04
athan_makubex19-May-13 9:04 
AnswerRe: VB.net 2010 form positioning Pin
Richard MacCutchan19-May-13 9:39
mveRichard MacCutchan19-May-13 9:39 
AnswerRe: VB.net 2010 form positioning Pin
NotPolitcallyCorrect19-May-13 10:51
NotPolitcallyCorrect19-May-13 10:51 
AnswerRe: VB.net 2010 form positioning Pin
claudiotronic19-May-13 20:37
claudiotronic19-May-13 20:37 
Questionneed VBA code!!! Pin
ssrd217-May-13 0:05
ssrd217-May-13 0:05 
AnswerRe: need VBA code!!! Pin
Richard MacCutchan17-May-13 1:09
mveRichard MacCutchan17-May-13 1:09 
QuestionHow To Print the Contents of a datagridview Pin
Evord16-May-13 2:12
professionalEvord16-May-13 2:12 
Hi everybody, am going to show you a sample program which enables to print the contents of a datagridview, the program works properly despite a minor error which occurs before the printing is done it says OBJECT REFERENCE NOT SET TO AN INSTANCE OF AN OBJECT, although it does not prevent the program from meeting the purpose. i would like to share it with you, and atleast we can discus on how to remove that error.

The program is based on the customers table of the Northwind Database.

On my form there is a datagridview named Mydatagridview, A print button called btnPrint



Below is the VB code ..............



Imports System.Data.OleDb
Imports System.Drawing.Printing
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Text
Imports System.Windows.Forms
Imports System.Drawing


Public Class Form1

Private WithEvents printDocument1 As New PrintDocument
'Used to save left coordinates of columns
Dim arrColumnLefts = New ArrayList()
'Used to save column widths
Dim arrColumnWidths = New ArrayList()
'Used to get and set the datagridview cell height
Dim iCellHeight As Integer = 0
Dim iTotalWidth As Integer = 0
'Used as counter
Dim iCount As Integer = 0
Dim iRow As Integer = 0
'Used to check whether we are printing first page
Dim bFirstPage As Boolean = False
'Used to check whether we are printing a new page
Dim bNewPage As Boolean = False
'Used for the header height
Dim iHeaderHeight As Integer = 0

Dim strFormat = New StringFormat()



Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As New OleDb.OleDbConnection

con.ConnectionString = "provider=microsoft.jet.oledb.4.0; Data source= " & Application.StartupPath & "\Customers.mdb"

Dim ds As DataSet = New DataSet()
Dim dt As New DataTable
Dim da As OleDbDataAdapter = New OleDbDataAdapter("SELECT CompanyName,ContactName,Address,PostalCode,Phone from Customers2", con)
Me.WindowState = FormWindowState.Maximized

Try
da.Fill(ds, "dt")
da.Fill(ds, "Customers2")
MyDataGridView.DataSource = ds
MyDataGridView.DataMember = "dt"
Catch ex As Exception
MessageBox.Show("Operation failed: " + ex.ToString(), Application.ProductName + " - Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
Return
End Try
End Sub




Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
'Open the print dialogue
Dim MyPrintDialog = New PrintDialog()
MyPrintDialog.Document = printDocument1
MyPrintDialog.UseEXDialog = True
'Get the document
If Windows.Forms.DialogResult.OK = MyPrintDialog.ShowDialog() Then
printDocument1.DocumentName = "Test page print"
printDocument1.Print()
End If

End Sub

Private Sub printDocument1_BeginPrint(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles _
printDocument1.BeginPrint
' MsgBox("starting printpage")
Try

strFormat.Alignment = StringAlignment.Near
strFormat.LineAlignment = StringAlignment.Center
strFormat.Trimming = StringTrimming.EllipsisCharacter

arrColumnLefts.Clear()
arrColumnWidths.Clear()
iCellHeight = 0
bFirstPage = True
bNewPage = True

'Calculating Total Widths
iTotalWidth = 0

For Each dgvGridCol As DataGridViewColumn In MyDataGridView.Columns
iTotalWidth = iTotalWidth + dgvGridCol.Width
Next

Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

End Sub


Private Sub printDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles _
printDocument1.PrintPage

Try

'Set the left margin
Dim iLeftMargin As Integer = e.MarginBounds.Left
'Set the top margin
Dim iTopMargin As Integer = e.MarginBounds.Top
'Whether more pages have to print or not
Dim bMorePagesToPrint As Boolean = False
Dim iTmpWidth As Integer = 0

'For the first page to print set the cell width and header height
If bFirstPage = True Then

For Each Gridcol As DataGridViewColumn In MyDataGridView.Columns
iTmpWidth = CType(Math.Floor(CType(CType(Gridcol.Width, Double) / CType(iTotalWidth, Double) * CType(iTotalWidth, Double) * (CType(e.MarginBounds.Width, Double) / CType(iTotalWidth, Double)), Double)), Integer)

iHeaderHeight = CType((e.Graphics.MeasureString(Gridcol.HeaderText, Gridcol.InheritedStyle.Font, iTmpWidth).Height) + 11, Integer)

'Save width and height of headers
arrColumnLefts.Add(iLeftMargin)
arrColumnWidths.Add(iTmpWidth)
iLeftMargin = iLeftMargin + iTmpWidth
Next

End If

'Loop till all the grid rows not get printed
While iRow <= MyDataGridView.Rows.Count - 1

Dim GridRow As DataGridViewRow = MyDataGridView.Rows(iRow)
'Set the cell height
iCellHeight = GridRow.Height + 5
Dim iCount As Integer = 0
'Check whether the current page settings allo more rows to print

If iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top Then

bNewPage = True
bFirstPage = False
bMorePagesToPrint = True

Exit While

Else

If bNewPage = True Then

'Draw header
e.Graphics.DrawString("Fibre Requirements", New Font(MyDataGridView.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top - e.Graphics.MeasureString("Customer Summary", New Font(MyDataGridView.Font, FontStyle.Bold), e.MarginBounds.Width).Height - 13)

Dim strDate As String = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString()

'Draw Date
e.Graphics.DrawString(strDate, New Font(MyDataGridView.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(strDate, New Font(MyDataGridView.Font, FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top - e.Graphics.MeasureString("Customer Summary", New Font(New Font(MyDataGridView.Font, FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13)

'Draw Columns
iTopMargin = e.MarginBounds.Top

For Each GridCol As DataGridViewColumn In MyDataGridView.Columns

e.Graphics.FillRectangle(New SolidBrush(Color.LightGray), New Rectangle(CType(arrColumnLefts(iCount), Integer), iTopMargin, CType(arrColumnWidths(iCount), Integer), iHeaderHeight))

e.Graphics.DrawRectangle(Pens.Black, New Rectangle(CType(arrColumnLefts(iCount), Integer), iTopMargin, CType(arrColumnWidths(iCount), Integer), iHeaderHeight))

e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font, New SolidBrush(GridCol.InheritedStyle.ForeColor), New RectangleF(CType(arrColumnLefts(iCount), Integer), iTopMargin, CType(arrColumnWidths(iCount), Integer), iHeaderHeight), strFormat)
iCount = iCount + 1

Next GridCol

bNewPage = False
iTopMargin += iHeaderHeight

End If
iCount = 0

'Draw Columns Contents
For Each Cel As DataGridViewCell In GridRow.Cells

If Not IsDBNull(Cel.Value) Then

e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font, New SolidBrush(Cel.InheritedStyle.ForeColor), New RectangleF(CType(arrColumnLefts(iCount), Integer), CType(iTopMargin, Single), CType(arrColumnWidths(iCount), Integer), CType(iCellHeight, Single)), strFormat)

End If

'Drawing Cells Borders
e.Graphics.DrawRectangle(Pens.Black, New Rectangle(CType(arrColumnLefts(iCount), Integer), iTopMargin, CType(arrColumnWidths(iCount), Integer), iCellHeight))

iCount = iCount + 1

Next

End If

iRow = iRow + 1
iTopMargin = iTopMargin + iCellHeight

End While

'If more lines exist, print another page.
If bMorePagesToPrint = True Then

e.HasMorePages = True

Else

e.HasMorePages = False

End If

Catch exc As Exception

MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

End Try

End Sub

End Class
AnswerRe: How To Print the Contents of a datagridview Pin
Richard MacCutchan16-May-13 2:59
mveRichard MacCutchan16-May-13 2:59 
AnswerRe: How To Print the Contents of a datagridview Pin
Eddy Vluggen16-May-13 3:01
professionalEddy Vluggen16-May-13 3:01 
QuestionFinding Duplicate numbers Pin
CowlitzTroy13-May-13 21:29
CowlitzTroy13-May-13 21:29 
AnswerRe: Finding Duplicate numbers Pin
Dave Kreskowiak14-May-13 4:38
mveDave Kreskowiak14-May-13 4:38 
AnswerRe: Finding Duplicate numbers Pin
MicroVirus17-May-13 1:39
MicroVirus17-May-13 1:39 
GeneralRe: Finding Duplicate numbers Pin
Dave Kreskowiak17-May-13 2:19
mveDave Kreskowiak17-May-13 2:19 
QuestionLists of objects without losing class Intelli-sense Pin
Purge1t13-May-13 18:24
Purge1t13-May-13 18:24 
AnswerRe: Lists of objects without losing class Intelli-sense Pin
Dave Kreskowiak13-May-13 18:51
mveDave Kreskowiak13-May-13 18:51 
GeneralRe: Lists of objects without losing class Intelli-sense Pin
Purge1t13-May-13 19:21
Purge1t13-May-13 19:21 
GeneralRe: Lists of objects without losing class Intelli-sense Pin
Dave Kreskowiak14-May-13 3:44
mveDave Kreskowiak14-May-13 3:44 
GeneralRe: Lists of objects without losing class Intelli-sense Pin
Purge1t14-May-13 11:55
Purge1t14-May-13 11:55 
GeneralRe: Lists of objects without losing class Intelli-sense Pin
Dave Kreskowiak14-May-13 13:33
mveDave Kreskowiak14-May-13 13:33 
QuestionTryParse String from InputBox to Integer Pin
Member 1004983713-May-13 16:06
Member 1004983713-May-13 16:06 
AnswerRe: TryParse String from InputBox to Integer Pin
PIEBALDconsult13-May-13 17:30
mvePIEBALDconsult13-May-13 17:30 
QuestionHow to get values from listview and display it to textbox using sql database ? Pin
Member 1001708312-May-13 4:58
professionalMember 1001708312-May-13 4:58 
AnswerRe: How to get values from listview and display it to textbox using sql database ? Pin
Eddy Vluggen13-May-13 7:23
professionalEddy Vluggen13-May-13 7:23 
QuestionTreeView Find Starting from Some Child Node Pin
treddie11-May-13 21:20
treddie11-May-13 21:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.