sql datareader to list

eekamouse

New member
Joined
Jul 17, 2015
Messages
2
Programming Experience
1-3
How do I read the data from a datareader into a list. I am using vb.net. The app is a windows forms app. This is what I have been trying but to no avail.Using breakpoints I can see that the variables contain data and that items are being added to the list, but each item added to the list is empty. How do I resolve this? Thanks.
VB.NET:
Dim RM_Draw As Double
        Dim RM_SP As Integer
        Dim Finishing_Position As Integer
        Dim drawstats As New List(Of DrawStats)


        While (dr.Read())




            RM_Draw = dr.GetInt32(dr.GetOrdinal("RM_Draw"))
            RM_SP = dr.GetDecimal(dr.GetOrdinal("RM_SP"))
            Finishing_Position = dr.GetInt32(dr.GetOrdinal("Finishing_Position"))






            drawstats.Add(New DrawStats(drawstats))




        End While
 
I finally figured it out. Here, just in case it helps others with a similar issue, is what I came up with. It does work, though whether or not its the orthodox or best way of doing I can't say.

VB.NET:
Dim dd As New List(Of DrawStats)
      
        While (dr.Read())
            Dim d As New DrawStats
            ' Dim dd As List(Of DrawStats)

            RM_Draw = dr.GetInt32(dr.GetOrdinal("RM_Draw"))
            RM_SP = dr.GetDecimal(dr.GetOrdinal("RM_SP"))
            Finishing_Position = dr.GetInt32(dr.GetOrdinal("Finishing_Position"))
            d.RM_Draw = RM_Draw
            d.RM_SP = RM_SP
            d.Finishing_Position = Finishing_Position
            dd.Add(d)

        End While

And to support that the class

VB.NET:
Public Class DrawStats


    Public Property RM_Draw As Double
    Public Property RM_SP As Integer
    Public Property Finishing_Position As Integer


End Class

If there is a better way of achieving the same then I would welcome all suggestions. Thanks
 
That's basically correct, although what's the point of reading from the data reader to variables and then those variables to the item properties? Why not just go straight from the data reader to the item properties?

By the way, your data types are messed up. You have declared the RM_Draw property as type Double and yet call GetInt32 to get the data. You also declare RM_SP as type Integer and call GetDecimal to get the data. You call GetDouble for a Double, GetInt32 for an Integer and GetDecimal for a Decimal. It's OK to assign an Integer to a Double or Decimal variable or property but not the other way around.
 

Latest posts

Back
Top