vb.net 如何将数据读取器转换为数据表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9413195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:57:22  来源:igfitidea点击:

How to convert a datareader to datatable

vb.netasp.net-2.0

提问by jason

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

我有一个关于将 a 转换datareader为 a 的问题datatable。在我的代码中,我datareader在一个类中创建了一个并传递给另一个类,我想将其转换为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 datareaderto another function that it stops working. Is this because the dris closed or something? How do I overcome this problem? Any help would be great.

只有当我将 传递datareader给另一个函数时,它才会停止工作。这是因为dr关闭了还是什么?我如何克服这个问题?任何帮助都会很棒。

采纳答案by HndlCode

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

回答by Ben

Use DataTable Load()method.

使用数据表Load()方法。

 // Given a DataReader called "reader"
 DataTable dt = new DataTable();
 dt.Load(reader)