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
How to convert a datareader to datatable
提问by jason
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
.
我有一个关于将 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 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.
只有当我将 传递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)