Home > Software engineering >  Why is my data reader only returning one row?
Why is my data reader only returning one row?

Time:11-09

I am using SqlDataReader to show data in a RichTextBox, but I only get one row.

This is my code:

  Dim strsql As String
        Dim OrdenNumero As Integer
        Dim Articulo As String
        Dim con As New SqlConnection("")

        strsql = "SELECT * FROM OrdenesParaMonitor WHERE Orden# = (SELECT MAX(Orden#) from OrdenesParaMonitor);"

        Dim cmd As New SqlCommand(strsql, con)

        Dim myreader As SqlDataReader
        con.Open()
        myreader = cmd.ExecuteReader
        If myreader.HasRows = True Then
            While myreader.Read()
                OrdenNumero = myreader("Orden#")
                Articulo = myreader("Articulo")
                Label1.Text = OrdenNumero
                RichTextBox1.Text = Articulo


            End While
        End If
     End Sub

I know I have to loop if I want to read all the rows, but no one uses VB.NET so its hard to find a good example on how to do this as a beginner.

CodePudding user response:

Why is my data reader only returning one row?

It may not be, but you're overwriting the same set of variables and UI elements for each row. So you may only be seeing the last row after the While loop.

Debug your project and put a breakpoint inside the while loop to be sure.

no one uses VB.NET so its hard to find a good example on how to do this as a beginner.

Have you considered that C# might be a better language for you to learn, since there are so many more examples. VB.NET is mostly used by people with lots of experience programming in VB.NET and/or VBA.

CodePudding user response:

As I have told in my comment, the problem is how the code sets the text for the two controls. Setting the text without appending to the previous one, just replaces the current text with the data coming from the record and leaves just the last set.

Instead you should append to the current text. This could be done with &= operator for the label or using the specific AppendText method for the RichTextBox.

While myreader.Read()
    OrdenNumero = myreader("Orden#")
    Articulo = myreader("Articulo")
    Label1.Text &= OrdenNumero   ' Append to the previous text
    RichTextBox1.AppendText(Articulo)
    ' or add a newline at each step
    RichTextBox1.AppendText(Articulo & Environment.NewLine)

End While
  • Related