0

How would you write the code to read the data from a query and display each row in a separate label if you don't know how many rows the query result may contain? If you try to read one too many rows with the DataReader, it throws an excetion when you try to read the column data on the row that doesn't exist. I'm not sure how to code this.

If dr.HasRows Then
    dr.Read()
    LN2.Text = dr.Item("linenum").ToString
Else
    LN2.visible  = False         
End If

This example shows how I am loading the second row with the DataReader. This works if there are two rows of data, but if there is only one row of data, it throws an exception. I have a maximum of 12 rows of data but, but my actual query results may contain anywhere between 1 and 12 rows of data.

Steven Doggart
  • 43,358
  • 8
  • 68
  • 105

1 Answers1

1

The Read method returns a boolean indicating whether or not the read of the next row was successful. Therefore, you could change your code to something like this:

If dr.Read() Then
    LN2.Text = dr.Item("linenum").ToString
Else
    LN2.visible  = False         
End If

However, usually, in such cases, displaying varying numbers of rows of data in a fixed number of labels isn't the best approach. For instance, if you used a single ListBox control instead, all your loading code could be simplified to the following:

While dr.Read()
    ListBox1.Items.Add(dr.Item("linenum").ToString())
End While

If you need to show multiple columns of data for each row, I would recommend using either a ListView control (with the View property set to Details) or a DataGridView control.

Steven Doggart
  • 43,358
  • 8
  • 68
  • 105