Results 1 to 18 of 18

Thread: Using data from an SQL query in my code

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    137

    Using data from an SQL query in my code

    I am using PDFSharp and want to use a database to set some of the properties in PDFSharp class code.
    I have a table which I call CSize which holds all of the numeric values a some string values.
    I have a combobox that lists all of the variations and the user will choose the row in the combobox and the ID, which in have named CID is the Value member and the Selected value in the Combobox control.
    I need to use all of the fields in the query, but am not sure how to write the code to use these values in the following PDFSharp class.
    I have in some places not tried to use the query table output but the boxX, boxY, cellX, cellY I have, and they are not being read as the document produced is all in the top left corner.
    Can someone illustrate to me the syntax for extrating the data from the datatable.
    I apologise that I am relatively inexperienced and am a senior citzen, so I am slow to understand.


    Here is the code:
    Code:
    Imports PdfSharp
    Imports PdfSharp.Drawing
    Imports PdfSharp.Fonts
    Imports PdfSharp.PageOrientation
    Imports PdfSharp.PageSize
    Imports PdfSharp.Pdf
    Imports PdfSharp.Internal
    Imports PdfSharp.Drawing.Layout
    Imports System.Data.SqlClient
    Enum pageOrientation
        Landscape
        Portrait
    End Enum
    Enum Pagesize
        A4
        A5
    End Enum
    Public Class PrintFrm
        Private connectionString As String = "Data Source=DESKTOP-S7FRNAL\SQLEXPRESS;Initial Catalog=Verses_Find;Integrated Security=True"
        Public Property dt As Object
        Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
            MessageBox.Show(Replace(txbVerse.Text, Chr(13) & Chr(10), " VBCrLf "))
            Dim boxX As Integer
            Dim boxY As Integer
            Dim cellw As Integer
            Dim cellh As Integer
            Dim ort As String = Nothing
            Dim FSize As Integer
            Dim CFont As String = Nothing
            Dim TxtColorValue As String
            Dim sqlAdaptor As SqlDataAdapter
            Dim dt As New DataTable
            Dim CSizeSql As String = Nothing
            Dim cmd As Object = Nothing
            Dim CSizeValue As Integer
    
    ' the SQL code starts here:
            Using connection As New SqlConnection(connectionString)
                connection.Open()
                CSizeSql = $"SELECT CID, boxX, ort, Narrative FROM CSize WHERE CID = {CSizeValue}"
                sqlAdaptor = New SqlDataAdapter(CSizeSql, connection)
                dt = New DataTable()
                sqlAdaptor.Fill(dt)
            End Using
    
            Dim document As PdfDocument
            ' Create a new PDF document
            document = New PdfDocument()
            document.Info.Title = "Created with PDFsharp"
    
            ' Create an empty page
            Dim page As PdfPage = document.AddPage
    
            If ort = "L" Then
                page.Orientation = CType(pageOrientation.Landscape, PdfSharp.PageOrientation)
                page.Width = XUnit.FromMillimeter(297)
                page.Height = XUnit.FromMillimeter(210)
            Else
                page.Orientation = CType(pageOrientation.Portrait, PdfSharp.PageOrientation)
                page.Width = XUnit.FromMillimeter(210)
                page.Height = XUnit.FromMillimeter(297)
            End If
    
    
    
            ' Draw the text
            Dim Ftext As String = txbVerse.Text
    
    
    
            Dim gfx As XGraphics
            gfx = XGraphics.FromPdfPage(page)
            Dim tf As XTextFormatter
            tf = New XTextFormatter(gfx)
            Dim font As XFont = New XFont("Verdana", 20, XFontStyle.Bold)
            Dim rect As XRect
            rect = New XRect(boxX, boxY, cellw, cellh)
            gfx.DrawRectangle(XBrushes.SeaShell, rect)
            tf.Alignment = XParagraphAlignment.Center
            tf.DrawString("This is some text", font, XBrushes.Black, rect, XStringFormats.TopLeft)
    
            ' Save the document
            Dim filename As String = "verse.pdf"
            document.Save(filename)
    
            ' ...and start a viewer.
            Process.Start(filename)
        End Sub
    
        Private Sub btnPaste_Click(sender As Object, e As EventArgs) Handles btnPaste.Click
    
            ' Determine if there is any text in the Clipboard to paste into the text box.
            If Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) = True Then
                ' Determine if any text is selected in the text box.
                If txbVerse.SelectionLength > 0 Then
                    ' Ask user if they want to paste over currently selected text.
                    If MessageBox.Show("Do you want to paste over current selection?",
                        "Cut Example", MessageBoxButtons.YesNo) = DialogResult.No Then
                        ' Move selection to the point after the current selection and paste.
                        txbVerse.SelectionStart = txbVerse.SelectionStart +
                            txbVerse.SelectionLength
                    End If
                End If
                ' Paste current text in Clipboard into text box.
                txbVerse.Paste()
            End If
        End Sub
    
        Private Sub PrnForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'TODO: This line of code loads data into the 'ColorDataSet.TxtColor' table. You can move, or remove it, as needed.
            Me.TxtColorTableAdapter.Fill(Me.ColorDataSet.TxtColor)
            'TODO: This line of code loads data into the 'Verses_Find_Color_DataSet.TxtColor' table. You can move, or remove it, as needed.
            Me.CSizeTableAdapter.Fill(Me.Verses_FindDataSet.CSize)
            Dim Print As New PrintFrm
            Me.TopMost = True
            Me.WindowState = FormWindowState.Normal
    
            For Each oFont As FontFamily In FontFamily.Families 'This line populates the font combo with the system installed fonts
                cboFont.Items.Add(oFont.Name)
            Next
    
        End Sub
    
        Private Sub cboCSize_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCSize.SelectedIndexChanged
            Me.CSizeTableAdapter.Fill(Me.Verses_FindDataSet.CSize)
            Dim cboCSize As Integer
            Dim CSizeValue As Integer = cboCSize
    
        End Sub
    
        Private Sub cboColor_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboColor.SelectedIndexChanged
            ' Me.TxtColorTableAdapter.Fill(Me.ColorDataSet.TxtColor)
            Dim cboColor As Integer
            Dim TxtColorValue As Integer = cboColor
        End Sub
    
        Private Sub nudTop_ValueChanged(sender As Object, e As EventArgs)
            Dim nudTop As Integer
            Dim CTop As Integer = nudTop
    
        End Sub
    
        Private Sub nudFSize_ValueChanged(sender As Object, e As EventArgs) Handles nudFSize.ValueChanged
            Dim nudFSize As Integer
            Dim FSize As Integer = nudFSize
        End Sub
    
        Private Sub cboFont_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboFont.SelectedIndexChanged
            Dim CFont As String = cboFont.Text
        End Sub
    End Class
    Last edited by Rocky48; Jun 15th, 2019 at 12:29 PM. Reason: typo

  2. #2
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,508

    Re: Using data from an SQL query in my code

    You need to use a parameter to filter what you retrieve.

    Code:
                CSizeSql = "SELECT CID, boxX, ort, Narrative FROM CSize WHERE CID = @cid"
                sqlAdaptor = New SqlDataAdapter(CSizeSql, connection)
                dt = New DataTable()
               sqladapter.SelectCommand.Parameters.AddWithValue("@cid", valueFromCombobox)
    jmc has a good post to help you understand, http://www.vbforums.com/showthread.p...ses&highlight=

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    137

    Re: Using data from an SQL query in my code

    I'm assuming I have understood correctly, that @CID applies to the local T-SQL variable and the CSizeValue is the variable in the SelectedIndexChanged sub. You will noticed that I have added some other fields in the SELECT statement. These are the values that I need to input into the PDFSharp commands to print the verse.
    However when I run the code I get an exception on the line @ort. Is it because that one is a string and all the rest are integers?
    The parameterized query '(@CID int,@boxX int,@ort nvarchar(4000),@cellw int,@cellh int)SE' expects the parameter '@ort', which was not supplied.
    Code:
    Using connection As New SqlConnection(connectionString)
                connection.Open()
                CSizeSql = $"SELECT CID, boxX, cellw, cellh ort, Narrative FROM CSize WHERE CID = @CID"
                sqlAdaptor = New SqlDataAdapter(CSizeSql, connection)
                dt = New DataTable()
                sqlAdaptor.SelectCommand.Parameters.AddWithValue("@CID", CSizeValue)
                sqlAdaptor.SelectCommand.Parameters.AddWithValue("@boxX", boxXValue)
                sqlAdaptor.SelectCommand.Parameters.AddWithValue("@ort", ortValue)
                sqlAdaptor.SelectCommand.Parameters.AddWithValue("@cellw", cellwValue)
                sqlAdaptor.SelectCommand.Parameters.AddWithValue("@cellh", cellhValue)
    
                sqlAdaptor.Fill(dt)
            End Using
    Here is the sub that the value comes from.
    Code:
     Private Sub cboCSize_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCSize.SelectedIndexChanged
    
            Dim CSizeValue As Integer = CInt(cboCSize.SelectedValue)
    
        End Sub
    Does it make a difference that only the @CID comes from a combobox selection, whereas the rest are just values I am extracting from the database. In other words is there a different method for those retreved from the database?
    Last edited by Rocky48; Jun 18th, 2019 at 12:18 PM.

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    137

    Re: Using data from an SQL query in my code

    Previous post got posted twice! Deleted it!

  5. #5
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,508

    Re: Using data from an SQL query in my code

    Using connection As New SqlConnection(connectionString)
    connection.Open()
    CSizeSql = $"SELECT CID, boxX, cellw, cellh ort, Narrative FROM CSize WHERE CID = @CID"
    sqlAdaptor = New SqlDataAdapter(CSizeSql, connection)
    dt = New DataTable()
    sqlAdaptor.SelectCommand.Parameters.AddWithValue("@CID", CSizeValue)
    sqlAdaptor.SelectCommand.Parameters.AddWithValue("@boxX", boxXValue)
    sqlAdaptor.SelectCommand.Parameters.AddWithValue("@ort", ortValue)
    sqlAdaptor.SelectCommand.Parameters.AddWithValue("@cellw", cellwValue)
    sqlAdaptor.SelectCommand.Parameters.AddWithValue("@cellh", cellhValue)

    sqlAdaptor.Fill(dt)
    End Using
    How does this make any sense, your Select statement uses one parameter but you add five parameters to the select command?? Also, if you're getting an error you need to tell use what the error says.

    Have you read the code bank post by jmc that I provided a link for?

  6. #6

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    137

    Re: Using data from an SQL query in my code

    I did not understand that the @CID only applied to the WHERE part.
    Basically what I am trying to achieve is to retreive all of the fields in the SELECT query when the selected value in the combobox is chosen.
    Looking at the codebank I think that the 'Retrrieving multiple records that will be read and discarded' option would be the one I need, though will the values still be available once I have read them in the messagebox?

    Will this work?
    Code:
    Using connection As New SqlConnection(connectionString)
                Using command As New SqlCommand("SELECT CID, boxX, cellw, cellh ort, Narrative FROM CSize WHERE CID = @CID", connection)
                    connection.Open()
                    sqlAdaptor.SelectCommand.Parameters.AddWithValue("@CID", CSizeValue)
                    Using Reader As SqlDataReader = command.ExecuteReader()
                        While Reader.Read()
                            MessageBox.Show(String.Format("Data", Reader("CID"), Reader("boxX"), Reader("cellw"), Reader("cellh"), Reader("ort"), Reader("Narrative")))
                        End While
                    End Using
                End Using
            End Using
    Not sure about the Parameter part!
    Am I heading in the right direction?

  7. #7
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,508

    Re: Using data from an SQL query in my code

    Will this work?
    Surely you can answer that question. Run the code, did it work.

    You've went from using a DataTable to using a DataReader. Which do you want to use?

    As far as your code,
    Code:
    sqlAdaptor.SelectCommand.Parameters.AddWithValue("@CID", CSizeValue)
    Why are you adding a parameter to a DataAdapter that you don't even use. Wouldn't it make sense to add the parameter to the Command object.
    Code:
    command.Parameters.AddWithValue("@CID", CSizeValue)

  8. #8

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    137

    Re: Using data from an SQL query in my code

    Should of tested before posting last post!
    Can't obviously mix SqlCommand and sqlAdaptor!
    How do I get around that?

  9. #9
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,508

    Re: Using data from an SQL query in my code

    Code:
    How do I get around that?
    Get around what???

    I've showed you how to use parameters with a DataAdpter and parameters with a Command object. Choose one, test it. What don't you understand.

  10. #10
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,104

    Re: Using data from an SQL query in my code

    For that matter, the dataadapter uses a Command object. That's what the SelectCommand is.
    My usual boring signature: Nothing

  11. #11

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    137

    Re: Using data from an SQL query in my code

    You had already answered my question BEFORE I posted the post, and your post did not appear until I had posted.

    This is my lastest post

    In Post #6:
    Looking at the codebank I think that the 'Retrrieving multiple records that will be read and discarded' option would be the one I need, though will the values still be available once I have read them in the messagebox?
    Tried this but no errors, but it is ignoring the data from the SQL query, as is printing in the top left corner and the messagebox is not show until I close the form and its empty.
    Why?

  12. #12
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,508

    Re: Using data from an SQL query in my code

    Sorry but your last post did nothing but confuse me.

    Tried this but no errors,
    Tried what? Post your code.

    but it is ignoring the data from the SQL query
    What is ignoring the data.

    If your talking about this messagebox
    Code:
    Using connection As New SqlConnection(connectionString)
                Using command As New SqlCommand("SELECT CID, boxX, cellw, cellh ort, Narrative FROM CSize WHERE CID = @CID", connection)
                    connection.Open()
                    sqlAdaptor.SelectCommand.Parameters.AddWithValue("@CID", CSizeValue)
                    Using Reader As SqlDataReader = command.ExecuteReader()
                        While Reader.Read()
                            MessageBox.Show(String.Format("Data", Reader("CID"), Reader("boxX"), Reader("cellw"), Reader("cellh"), Reader("ort"), Reader("Narrative")))
                        End While
                    End Using
                End Using
            End Using
    Unless this code is in a different form or in the Form Closing event there is no way it will show when you close the form.

  13. #13

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    137

    Re: Using data from an SQL query in my code

    When I ran the code there were no errors.
    Here is the latest version of the code we are talking about:
    Code:
     Using connection As New SqlConnection(connectionString)
                Using command As New SqlCommand("SELECT CID, boxX, cellw, cellh ort, Narrative FROM CSize WHERE CID = @CID", connection)
                    connection.Open()
                    command.Parameters.AddWithValue("@CID", CSizeValue)
                    Using Reader As SqlDataReader = command.ExecuteReader()
                        While Reader.Read()
                            MessageBox.Show(String.Format("Data", Reader("CID"), Reader("boxX"), Reader("cellw"), Reader("cellh"), Reader("ort"), Reader("Narrative")))
                        End While
                    End Using
                End Using
            End Using
    BUT YOUR STILL NOT ANSWERING THE MOST IMPORTANT PART OF MY POST!!
    As the messagebox was EMPTY when I closed the form:
    1) The data from the SELECT query was not used by the reader
    2) If this was working correctly, can I use the values used in the messagebox elsewhere in the form. That is in the following code from the PDFSharp class:
    Code:
     Dim document As PdfDocument
            ' Create a new PDF document
            document = New PdfDocument()
            document.Info.Title = "Created with PDFsharp"
    
            ' Create an empty page
            Dim page As PdfPage = document.AddPage
    
            If ort = "L" Then          ' <<<<Here
                page.Orientation = CType(pageOrientation.Landscape, PdfSharp.PageOrientation)
                page.Width = XUnit.FromMillimeter(297)
                page.Height = XUnit.FromMillimeter(210)
            Else
                page.Orientation = CType(pageOrientation.Portrait, PdfSharp.PageOrientation)
                page.Width = XUnit.FromMillimeter(210)
                page.Height = XUnit.FromMillimeter(297)
            End If
    
    
    
            ' Draw the text
            Dim Ftext As String = txbVerse.Text
    
    
    
            Dim gfx As XGraphics
            gfx = XGraphics.FromPdfPage(page)
            Dim tf As XTextFormatter
            tf = New XTextFormatter(gfx)
            Dim font As XFont = New XFont("Verdana", 20, XFontStyle.Bold)
            Dim rect As XRect
            rect = New XRect(boxX, CTop, cellw, cellh)            '<<< Here
            gfx.DrawRectangle(XBrushes.SeaShell, rect)
            tf.Alignment = XParagraphAlignment.Center
            tf.DrawString(Ftext, font, XBrushes.Black, rect, XStringFormats.TopLeft)
    
            ' Save the document
            Dim filename As String = "verse.pdf"
            document.Save(filename)
    
            ' ...and start a viewer.
            Process.Start(filename)
        End Sub

  14. #14
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,104

    Re: Using data from an SQL query in my code

    Not like that, no.

    The datareader exists ONLY during the Using block, then it is gone. So, the values returned by the reader have to be put somewhere else if you want to use them anywhere else in the program. A datatable would be the obvious choice, and a dataadapter is the more typical way to fill a datatable, but you CAN fill a datatable from a datareader:
    Code:
    yourDatatable.Load(Reader)
    If you do that in the Using block while the datareader is open, and if the datatable is declared outside of the method, such as at form scope, then the data in the datatable will be the data from the datareader, and will be available throughout the form.

    However, you'd have to get rid of that whole While loop. Datareaders are single pass, so I don't believe you can fill the datatable AND show the data with each row at the same time. Of course, you were probably only using that while loop for testing.
    My usual boring signature: Nothing

  15. #15
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,508

    Re: Using data from an SQL query in my code

    What I would do is have data retrieval in one method and the printing in another.

    Here is a working example using one of my databases but I'm sure you can see how to convert it to use yours.
    Code:
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
            Dim bId As Integer = CInt(Me.ComboBox2.SelectedValue)
    
            Using con As New SqlConnection(My.Settings.BooksDBConnectionString), da As New SqlDataAdapter("Select BookId, BookName, Author From Books WHERE BookID = @id", con), dt As New DataTable
                da.SelectCommand.Parameters.AddWithValue("@id", bId)
                da.Fill(dt)
                If dt.Rows.Count > 0 Then
                    Dim row As DataRow = dt.Rows(0)
                    printIt(row)
                End If
            End Using
        End Sub
    
    
        Private Sub printIt(row As DataRow)
            Dim id As Integer = CInt(row("bookid"))
            Dim bookname As String = row("bookname").ToString
            MessageBox.Show(id.ToString & "  " & bookname.ToString)
        End Sub

  16. #16

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    137

    Re: Using data from an SQL query in my code

    I have tried as wes4dbt suggested and I get no errors, but I am not getting any PDF file generated!
    As there are no exceptions I have nothing to debug.
    When I click the Print button nothing happens.
    One thing that happens that I cant explain is that I have added message boxes to all of the controls (Combo's and Numeric Up Down) and when I first run and before the Form appears the message boxes are shown in the following sequence:
    Font Size 18
    Font Size 24
    Top 20
    Top 50
    Font Size 18
    Font Size 24
    Top 20
    Top 50
    Color Error
    CSize 0
    The first number in each sequence is the minimum value, the second the displayed value.

    I suspect that the problem is in the database reteval!
    Also would it have made any difference that I moved the Subroutines, so that they were in a more logical order?
    Here is the up to date Code:
    Code:
    Imports PdfSharp
    Imports PdfSharp.Drawing
    Imports PdfSharp.Fonts
    Imports PdfSharp.PageOrientation
    Imports PdfSharp.PageSize
    Imports PdfSharp.Pdf
    Imports PdfSharp.Internal
    Imports PdfSharp.Drawing.Layout
    Imports System.Data.SqlClient
    Enum pageOrientation
        Landscape
        Portrait
    End Enum
    Enum Pagesize
        A4
        A5
    End Enum
    Public Class PrintFrm
        Private boxX As Integer
        Private boxY As Integer
        Private cellw As Integer
        Private cellh As Integer
        Private ort As String = Nothing
        Private FSize As Integer
        Private CFont As String = Nothing
        Private TxtColorValue As String
        Private sqlAdaptor As SqlDataAdapter
        Private dt As New DataTable
        Private CSizeSql As String = Nothing
        Private cmd As Object = Nothing
        Private CSizeValue As Integer
        Private Narrative As String = Nothing
        Private CID As Integer
        Private Y As Double
        Private connectionString As String = "Data Source=DESKTOP-S7FRNAL\SQLEXPRESS;Initial Catalog=Verses_Find;Integrated Security=True"
        Private Sub PrnForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'TODO: This line of code loads data into the 'ColorDataSet.TxtColor' table. You can move, or remove it, as needed.
            Me.TxtColorTableAdapter.Fill(Me.ColorDataSet.TxtColor)
            'TODO: This line of code loads data into the 'Verses_Find_Color_DataSet.TxtColor' table. You can move, or remove it, as needed.
            Me.CSizeTableAdapter.Fill(Me.Verses_FindDataSet.CSize)
            Dim Print As New PrintFrm
            Me.TopMost = True
            Me.WindowState = FormWindowState.Normal
    
            For Each oFont As FontFamily In FontFamily.Families 'This line populates the font combo with the system installed fonts
                cboFont.Items.Add(oFont.Name)
            Next
    
        End Sub
        Private Sub btnPaste_Click(sender As Object, e As EventArgs) Handles btnPaste.Click
    
            ' Determine if there is any text in the Clipboard to paste into the text box.
            If Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) = True Then
                ' Determine if any text is selected in the text box.
                If txbVerse.SelectionLength > 0 Then
                    ' Ask user if they want to paste over currently selected text.
                    If MessageBox.Show("Do you want to paste over current selection?",
                        "Cut Example", MessageBoxButtons.YesNo) = DialogResult.No Then
                        ' Move selection to the point after the current selection and paste.
                        txbVerse.SelectionStart = txbVerse.SelectionStart + txbVerse.SelectionLength
                    End If
                End If
                ' Paste current text in Clipboard into text box.
                txbVerse.Paste()
            End If
        End Sub
        Private Sub cboCSize_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCSize.SelectedIndexChanged
    
            Dim CSizeValue As Integer = CInt(cboCSize.SelectedValue)
            MessageBox.Show("CSize", CStr(CSizeValue))
        End Sub
    
        Private Sub cboColor_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboColor.SelectedIndexChanged
            Dim TxtColor As String = CStr(cboColor.SelectedValue)
            MessageBox.Show("Color", TxtColor)
    
        End Sub
        Private Sub nudFSize_ValueChanged(sender As Object, e As EventArgs) Handles nudFSize.ValueChanged
            Dim nudFSize1 As NumericUpDown = nudFSize
            Dim Fsize As Integer = CInt(nudFSize1.Value)
            MessageBox.Show("Font Size", CStr(Fsize))
        End Sub
    
        Private Sub cboFont_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboFont.SelectedIndexChanged
            Dim CFont As String = cboFont.Text
            MessageBox.Show("Font", CFont)
        End Sub
    
        Private Sub nudTop_ValueChanged_1(sender As Object, e As EventArgs) Handles nudTop.ValueChanged
            Dim Y As Double = CDbl(nudTop.Value)
            MessageBox.Show("Top", CStr(Y))
        End Sub
    
        Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
    
            Using connection As New SqlConnection(connectionString), da As New SqlDataAdapter("SELECT CID, boxX, cellw, cellh ort, Narrative FROM CSize WHERE CID = @CID", connection), dt As New DataTable
                connection.Open()
    
                da.SelectCommand.Parameters.AddWithValue("@CID", CSizeValue)
                da.Fill(dt)
                If dt.Rows.Count > 0 Then
                    Dim row As DataRow = dt.Rows(0)
                    printIt(row)
    
                End If
            End Using
        End Sub
        Private Sub printIt(row As DataRow)
            Dim ID As Double = CDbl(row("CID"))
            Dim X As Double = CDbl(row("boxX"))
            Dim W As Double = CDbl(row("cellw"))
            Dim H As Double = CDbl(row("cellh"))
            Dim O As String = CStr(row("ort"))
            Dim N As String = CStr(row("Narrative"))
            'MessageBox.Show("Data", CID.ToString & " " & boxX.ToString & " " & cellw.ToString & " " & cellh & " " & ort.ToString & " " & Narrative.ToString)
            Replace(txbVerse.Text, Chr(13) & Chr(10), " VBCrLf ")
            Dim document As PdfDocument
            ' Create a new PDF document
            document = New PdfDocument()
            document.Info.Title = "Created with PDFsharp"
    
            ' Create an empty page
            Dim page As PdfPage = document.AddPage
    
            If O = "L" Then
                page.Orientation = CType(pageOrientation.Landscape, PdfSharp.PageOrientation)
                page.Width = XUnit.FromMillimeter(297)
                page.Height = XUnit.FromMillimeter(210)
            Else
                page.Orientation = CType(pageOrientation.Portrait, PdfSharp.PageOrientation)
                page.Width = XUnit.FromMillimeter(210)
                page.Height = XUnit.FromMillimeter(297)
            End If
    
    
    
            ' Draw the text
            Dim Ftext As String = txbVerse.Text
    
    
    
            Dim gfx As XGraphics
            gfx = XGraphics.FromPdfPage(page)
            Dim tf As XTextFormatter
            tf = New XTextFormatter(gfx)
            Dim font As XFont = New XFont(CFont, FSize, XFontStyle.Bold)
            Dim rect As XRect
            rect = New XRect(X, Y, W, H)
            gfx.DrawRectangle(XBrushes.SeaShell, rect)
            tf.Alignment = XParagraphAlignment.Center
            tf.DrawString(Ftext, font, XBrushes.Blue, rect, XStringFormats.TopLeft)
    
            ' Save the document
            Dim filename As String = "verse.pdf"
            document.Save(filename)
    
            ' ...and start a viewer.
            Process.Start(filename)
        End Sub
    End Class
    Do these outputs from the output window mean anything:
    The thread 0x20a0 has exited with code 0 (0x0).
    The thread 0x1958 has exited with code 0 (0x0).
    The thread 0x38bc has exited with code 0 (0x0).
    The thread 0x48d0 has exited with code 0 (0x0).
    The thread 0x3dec has exited with code 0 (0x0).
    The thread 0x3c88 has exited with code 0 (0x0).
    The thread 0x5220 has exited with code 0 (0x0).
    The thread 0x5088 has exited with code 0 (0x0).
    The thread 0x26b4 has exited with code 0 (0x0).
    The thread 0xdf0 has exited with code 0 (0x0).
    The thread 0x42f8 has exited with code 0 (0x0).
    The thread 0x42a4 has exited with code 0 (0x0).
    The thread 0x64 has exited with code 0 (0x0).
    The thread 0x3698 has exited with code 0 (0x0).
    The thread 0x2018 has exited with code 0 (0x0).
    The thread 0x2fc8 has exited with code 0 (0x0).
    The thread 0x1484 has exited with code 0 (0x0).
    The thread 0x3408 has exited with code 0 (0x0).
    The thread 0x4318 has exited with code 0 (0x0).
    The thread 0x4f60 has exited with code 0 (0x0).
    The thread 0x394c has exited with code 0 (0x0).
    The thread 0x29d4 has exited with code 0 (0x0).
    The thread 0x3340 has exited with code 0 (0x0).
    The thread 0xbe4 has exited with code 0 (0x0).
    The thread 0xa88 has exited with code 0 (0x0).
    The thread 0x4d98 has exited with code 0 (0x0).
    The thread 0x27fc has exited with code 0 (0x0).
    The thread 0x1408 has exited with code 0 (0x0).


    Is there any other ways of seeing what is going on?
    Please help.

  17. #17
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,630

    Re: Using data from an SQL query in my code

    Quote Originally Posted by Rocky48 View Post
    I have tried as wes4dbt suggested and I get no errors, but I am not getting any PDF file generated!
    As there are no exceptions I have nothing to debug.
    When I click the Print button nothing happens.
    I'm not sure you understand what debugging means. You can have code that doesn't throw an exception but still has bugs. Debugging code is akin to starting a car, popping the hood, and looking around at all the belts and parts etc. while the car is running.

    Code:
        Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
    
            Using connection As New SqlConnection(connectionString), da As New SqlDataAdapter("SELECT CID, boxX, cellw, cellh ort, Narrative FROM CSize WHERE CID = @CID", connection), dt As New DataTable
                connection.Open()
    
                da.SelectCommand.Parameters.AddWithValue("@CID", CSizeValue)
                da.Fill(dt)
                If dt.Rows.Count > 0 Then
                    Dim row As DataRow = dt.Rows(0)
                    printIt(row)
    
                End If
            End Using
        End Sub
    You need to add a breakpoint on the "If dt.Rows.Count" line above and examine two things:

    1. The value of CSizeValue when this sub is running. Spoiler alert - the value WILL be 0. And it is because you still have ignored the advice of several people here to take a step back and try to understand the concept of variable scope.

    2. The value of dt.Rows.Count, which will almost certainly be 0, but since I can't see into your database, that's just a best guess.

    This will likely be my last attempt to give you useful advice. Good luck.

  18. #18
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,508

    Re: Using data from an SQL query in my code

    Yeah, you have two different CSizeValue variables,

    This one is a Local variable or Procedure Scope
    Code:
        Private Sub cboCSize_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCSize.SelectedIndexChanged
    
            Dim CSizeValue As Integer = CInt(cboCSize.SelectedValue)
            MessageBox.Show("CSize", CStr(CSizeValue))
        End Sub
    As soon as you exit that procedure, CSizeValue no longer exists.

    The you have a CSizeValue variable that has Form level Scope
    Code:
    Private CSizeValue As Integer
    This variable can be used anywhere inside the class (form).

    What you need to be doing is using the CSizeValue with form level scope,

    Code:
        Private Sub cboCSize_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCSize.SelectedIndexChanged
    
            CSizeValue = CInt(cboCSize.SelectedValue)
            MessageBox.Show("CSize", CStr(CSizeValue))
        End Sub
    You also need to remove all those MessageBoxes. You need to start using BreakPoints to debug code. I'm sure you can find information on how to use breakpoints. Basically all you have to do is click on the far left of the line of code you want the program to stop at. Then you can examine the values of the vatiables by hovering the mouse pointer over them.

    I would put a break point at this line and examine the value of CSizeValue.
    Code:
    da.SelectCommand.Parameters.AddWithValue("@CID", CSizeValue)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width