Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Add print button and Printing from a ListBox

Posted on 2008-10-21
7
Medium Priority
?
1,650 Views
Last Modified: 2012-08-14
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
Comment
Question by:ucla11
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
7 Comments
 
LVL 18

Expert Comment

by:vbturbo
ID: 22787317
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
 

Author Comment

by:ucla11
ID: 22792774
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
 
LVL 18

Accepted Solution

by:
vbturbo earned 2000 total points
ID: 22797826
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 18

Expert Comment

by:vbturbo
ID: 22797836
and in the top of your class - add this

Imports System.Drawing.Printing

0
 

Author Comment

by:ucla11
ID: 22806128
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
 

Author Comment

by:ucla11
ID: 22806151
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
 
LVL 18

Expert Comment

by:vbturbo
ID: 22806601

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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question