vb.netasp.net-2.0

How to convert a datareader to datatable


I have a question about converting a datareader to a datatable. In my code, I have a datareader created in one class and passed to another class that I want to convert it to a datatable.

When I do this, it does not seem to work, as the table remains empty. If I do the conversion in the same function, it works fine.

Its only when I pass the datareader to another function that it stops working. Is this because the dr is closed or something? How do I overcome this problem? Any help would be great.


Solution

  • Check this out:

    Public Function ExecuteQuery(ByVal s As String, ByVal condb As SqlConnection, ByVal ParamArray params() As SqlParameter) As DataTable
            Dim dt As DataTable = Nothing
            Using da As New System.Data.SqlClient.SqlDataAdapter(s, condb)               
                dt = New DataTable
                If params.Length > 0 Then
                    da.SelectCommand.Parameters.AddRange(params)
                End If
                If da.SelectCommand.Connection.State <> ConnectionState.Open Then da.SelectCommand.Connection.Open()
                da.Fill(dt)                    
            End Using
            Return dt
    End Function