• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1660
  • Last Modified:

Add print button and Printing from a ListBox

I use VB.net every once in awhile to make programs for my kids.  So my skill level varies at times.  I made a state and capitals game. A long time ago and now my youngest child is learning the States and Capitals.  Her teacher wants to use the game in school but I feel it is not that robust.  Needs tweaks here and there. So I'll start with this problem. On the main form there is a button that shows your correct answers when you click on this button it open another form that shows correct answers in a listbox, I want  have a print button on that form and to print the contents of listbox called lstAnwsers.  Actually I would also like also the incorrect ones on the printed page separated by tiles Correct answers and Incorrect answers. I also have a form that loads first when you open the game so that the player can type in their name in a textbox called txtReplace. So perhaps place their name on top page.

This code populates correct answer listbox  and removes states and capitals their listboxes once player enters a correct choice, they select state in one listbox  and capital in another listbox then click a button to check there answer, these listboxes are side by side on main form.  Crude but it works"

If lstStates.SelectedItem = "Alabama" And lstCapitals.SelectedItem = "Montgomery" Then
            'adds to list box' CorrectAnwsers.lstAnwsers.Items.Add(lstStates.SelectedItem & " - " & lstCapitals.SelectedItem)
            lstCapitals.Items.RemoveAt(lstCapitals.SelectedIndex)
            lstStates.Items.RemoveAt(lstStates.SelectedIndex)
            lblCorrect.Visible = True
            lblWrong.Visible = False

        ElseIf lstStates.SelectedItem = "Alaska" And lstCapitals.SelectedItem = "Juneau" Then
            CorrectAnwsers.lstAnwsers.Items.Add(lstStates.SelectedItem & " - " & lstCapitals.SelectedItem)
            lstCapitals.Items.RemoveAt(lstCapitals.SelectedIndex)
            lstStates.Items.RemoveAt(lstStates.SelectedIndex)
            lblCorrect.Visible = True
            lblWrong.Visible = False

'and so on for each state...........'

The game uses different play versions one is 50 tries, another is on a timer (one minute to five minutes) and unlimited tries. Once the player runs out of time or usestheir tries the states and capital that were not correct remain in their listboxes. so how could I add these to a listbox then print them on the same "results" page.  I don't know how to the unlimited try version, perhaps have Quit button and then populate incorrect listbox.

Thanks for your input
0
ucla11
Asked:
ucla11
  • 4
  • 3
1 Solution
 
vbturboCommented:
Try this

Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim LeftMargin As Single = e.MarginBounds.Left
        Dim TopMargin As Single = e.MarginBounds.Top
        Dim MyLines As Single = 0
        Dim YPosition As Single = 0
        Dim Counter As Integer = 0
        Dim CurrentLine As String
        Dim myFont As New Font("Courier New", 16, FontStyle.Regular, GraphicsUnit.Pixel)
        'calculate number of lines
        MyLines = e.MarginBounds.Height / myFont.GetHeight(e.Graphics)
        'Prints each line of file, but stops at end of page
        While ItemCounter <= lstDisplay.Items.Count - 1
            CurrentLine = CType(lstDisplay.Items(ItemCounter), String)
            YPosition = TopMargin + Counter * myFont.GetHeight(e.Graphics)
            e.Graphics.DrawString(CurrentLine, myFont, Brushes.Black, LeftMargin, YPosition, New StringFormat())
            Counter += 1
            ItemCounter += 1
        End While
        'if more line exist, print more pages
        If Not (ItemCounter = lstDisplay.Items.Count) Then
            e.HasMorePages = True
        Else
            e.HasMorePages = False
        End If

    End Sub

    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click

        Me.PrintDocument1.Print()

    End Sub

vbturbo
0
 
ucla11Author Commented:
I get an error message saying  Handles clause requires a WithEvents variable defined in the containing type or one of its base types
Handles PrintDocument1.PrintPage...... PrintDocument1 has a sqiggly line under it showing an error

I am using VB.net stuido 2008


    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim LeftMargin As Single = e.MarginBounds.Left
        Dim TopMargin As Single = e.MarginBounds.Top
        Dim MyLines As Single = 0
        Dim YPosition As Single = 0
        Dim Counter As Integer = 0
        Dim CurrentLine As String
        Dim m_intItemCounter As Integer
        Dim myFont As New Font("Courier New", 16, FontStyle.Regular, GraphicsUnit.Pixel)
        'calculate number of lines
        MyLines = e.MarginBounds.Height / myFont.GetHeight(e.Graphics)
        'Prints each line of file, but stops at end of page
        While m_intItemCounter <= lstAnwsers.Items.Count - 1
            CurrentLine = CType(lstAnwsers.Items(m_intItemCounter), String)
            YPosition = TopMargin + Counter * myFont.GetHeight(e.Graphics)
            e.Graphics.DrawString(CurrentLine, myFont, Brushes.Black, LeftMargin, YPosition, New StringFormat())
            Counter += 1
            m_intItemCounter += 1
        End While
        'if more line exist, print more pages
        If Not (m_intItemCounter = lstAnwsers.Items.Count) Then
            e.HasMorePages = True
        Else
            e.HasMorePages = False
        End If

    End Sub
0
 
vbturboCommented:
sorry

    Dim itemcounter As Integer
    Dim LeftMargin As Integer = 50

  Private Sub PrintDocument1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintDocument1.Click
        Try
            ' Assumes the default printer.
            Dim pd As New PrintDocument()
            AddHandler pd.PrintPage, AddressOf Me.pd_PrintPage
            pd.Print()
        Catch ex As Exception
            MessageBox.Show("An error occurred while printing", _
                ex.ToString())
        End Try

    End Sub

    ' Specifies what happens when the PrintPage event is raised.
    Private Sub pd_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs)
        Dim TopMargin As Single = e.MarginBounds.Top
        Dim MyLines As Single = 0
        Dim YPosition As Single = 0
        Dim Counter As Integer = 0
        Dim CurrentLine As String
        Dim myFont As New Font("Courier New", 16, FontStyle.Regular, GraphicsUnit.Pixel)
        'calculate number of lines
        MyLines = e.MarginBounds.Height / myFont.GetHeight(e.Graphics)
        'Prints each line of file, but stops at end of page
        While itemcounter <= lstDisplay.Items.Count - 1
            CurrentLine = CType(lstDisplay.Items(itemcounter), String)
            YPosition = TopMargin + Counter * myFont.GetHeight(e.Graphics)
            e.Graphics.DrawString(CurrentLine, myFont, Brushes.Black, LeftMargin, YPosition, New StringFormat())
            Counter += 1
            itemcounter += 1
        End While
        'if more line exist, print more pages
        If Not (itemcounter = lstDisplay.Items.Count) Then
            e.HasMorePages = True
        Else
            e.HasMorePages = False
        End If
    End Sub
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
vbturboCommented:
and in the top of your class - add this

Imports System.Drawing.Printing

0
 
ucla11Author Commented:
When I print the intems from list box I want to print plyers name at top of page followed b the date on next line folled by the text "Your Correct Anwsers" then the list of correct anwsers.  then and seccond tiltle "you Inccorrect Anwser" followed the remaining contents of lstStates ( the that were not moved to the correct anwser list box) every wors fine with the code you gave I change it to print Players name but when I try to print todays date on next line it prints over the players name so i just added it the same line.  Thanks.....
0
 
ucla11Author Commented:
Let me correct my spellin errors.........
When I print the intems from list box I want to print players name at top of page followed by the date on next line followed by the text "Your Correct Anwsers" then the list of correct anwsers.from  lstCorrectAnwsers then and seccond tiltle "you Inccorrect Anwser" followed  the remaining contents of lstStates ( the that were not moved to the correct anwser list box) every works fine with the code you gave me.  I changed it to print Players name at top, but when I try to print todays date on next line it prints over the players name so i just added it the same line.  Thanks.....  here the code

Private Sub btnPrintCorrect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrintCorrect.Click
        Try
            ' Assumes the default printer.
            Dim pd As New PrintDocument()
            AddHandler pd.PrintPage, AddressOf Me.pd_PrintPage
            pd.Print()
        Catch ex As Exception
            MessageBox.Show("An error occurred while printing", _
                ex.ToString())
        End Try

    End Sub

    ' Specifies what happens when the PrintPage event is raised.
    Private Sub pd_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs)

        Dim itemcounter As Integer

        Dim LeftMargin As Integer = 50
        Dim TopMargin As Single = e.MarginBounds.Top
        Dim MyLines As Single = 0
        Dim YPosition As Single = 0
        Dim YpositionName As Single = 0
        Dim Counter As Integer = 0
        Dim Counter2 As Integer = 0
        Dim CurrentLine As String
        Dim PlayersName As String
        Dim myFont As New Font("Arial", 16, FontStyle.Bold, GraphicsUnit.Pixel)
        Dim myFontPlayer As New Font("Arial", 18, FontStyle.Bold, GraphicsUnit.Pixel)

        'calculate number of lines
        MyLines = e.MarginBounds.Height / myFont.GetHeight(e.Graphics)

        'Prints players name and date
        YpositionName = TopMargin + Counter * myFontPlayer.GetHeight(e.Graphics)
        PlayersName = CType(lblPlayer.Text & "'s" & " correct anwsers  " & "on " & Today, String)
        e.Graphics.DrawString(PlayersName, myFontPlayer, Brushes.Black, LeftMargin, YpositionName, New StringFormat())
        '  to drop list of anwsers dow?    Counter += 5

        'Prints each line of file, but stops at end of page
        While itemcounter <= lstCorrectAnwsers.Items.Count - 1
            CurrentLine = CType(lstCorrectAnwsers.Items(itemcounter), String)
            YPosition = TopMargin + Counter * myFont.GetHeight(e.Graphics)
            e.Graphics.DrawString(CurrentLine, myFont, Brushes.Black, LeftMargin, YPosition, New StringFormat())
            Counter += 1
            itemcounter += 1
        End While

        'if more line exist, print more pages
        If Not (itemcounter = lstCorrectAnwsers.Items.Count) Then
            e.HasMorePages = True
        Else
            e.HasMorePages = False

        End If
    End Sub
0
 
vbturboCommented:

try play with this

   Dim dlg As New PrintPreviewDialog()
    Private WithEvents mDoc As New PrintDocument()
    Private mFont As New Font("Courier New", 12)
    Private Sub PrintDocument1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintDocument1.Click
        Try

            dlg.Document = mDoc
            dlg.ShowDialog()
            'mDoc.Print()

        Catch ex As Exception
            MessageBox.Show("An error occurred while printing", _
                ex.ToString())
        End Try

    End Sub
    Private Sub mDoc_BeginPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles mDoc.BeginPrint

    End Sub
    Private Sub mDoc_EndPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles mDoc.EndPrint

    End Sub
    ' Specifies what happens when the PrintPage event is raised.
    Private Sub mDoc_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs) Handles mDoc.PrintPage

        Dim myFont As New Font("Courier New", 16, FontStyle.Regular, GraphicsUnit.Pixel)
        Dim textHeight As Integer = e.Graphics.MeasureString("W", myFont).Height
        Dim value As String = ""

        value = "      This is a test" & Space(25) & "And scores"
        e.Graphics.DrawString(value, myFont, Brushes.Black, 10, 5)

        Dim blackPen As New Pen(Color.Black, 1)

        ' Create points that define line.
        Dim point1 As New Point(10, 60)
        Dim point2 As New Point(815, 60)

        ' Draw line to screen.
        e.Graphics.DrawLine(blackPen, point1, point2)

        Dim mFont As New Font("Arial", 10)
        Dim TopMargin As Single = e.MarginBounds.Top
        Dim MyLines As Single = 0
        Dim YPosition As Single = 0
        Dim Counter As Integer = 0
        Dim CurrentLine As String

        'calculate number of lines
        MyLines = e.MarginBounds.Height / myFont.GetHeight(e.Graphics)
        'Prints each line of file, but stops at end of page
        While itemcounter <= lstDisplay.Items.Count - 1
            CurrentLine = CType(lstDisplay.Items(itemcounter), String)
            YPosition = TopMargin + Counter * myFont.GetHeight(e.Graphics)
            e.Graphics.DrawString(CurrentLine, myFont, Brushes.Black, LeftMargin, YPosition, New StringFormat())
            Counter += 1
            itemcounter += 1
        End While
        'if more line exist, print more pages
        If Not (itemcounter = lstDisplay.Items.Count) Then
            e.HasMorePages = True
        Else
            e.HasMorePages = False
        End If

    End Sub

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now