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.
The
Readmethod 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: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
ListBoxcontrol instead, all your loading code could be simplified to the following:If you need to show multiple columns of data for each row, I would recommend using either a
ListViewcontrol (with theViewproperty set toDetails) or aDataGridViewcontrol.