将数据绑定到 ReportViewer 控件的最佳方法是什么? (数据适配器与数据读取器)
我有两种方法将数据绑定到 ReportViewer 控件。哪一个更好?您能给我一些建议吗?
方法 1:使用 SqlDataAdapter
Dim dt As DataTable = New DataTable
Dim conn As SqlConnection = New SqlConnection(connString)
Try
conn.Open()
Dim cmd As New SqlCommand(sql, conn)
Dim adapter As New SqlDataAdapter(cmd)
adapter.Fill(dt)
Catch ex As Exception
Finally
conn.Close()
End Try
Dim ds As New ReportDataSource(dataSourceName, dt)
rViewer.LocalReport.DataSources.Clear()
rViewer.LocalReport.DataSources.Add(ds)
rViewer.LocalReport.Refresh()
方法 2:使用 SqlDataReader
Dim dt As New DataTable()
Dim conn As SqlConnection = New SqlConnection(connString)
Try
conn.Open()
Dim cmd As New SqlCommand(sql, conn)
Dim reader As SqlDataReader = cmd.ExecuteReader()
dt.Load(reader)
reader.Close()
Catch ex As Exception
Finally
conn.Close()
End Try
Dim ds As New ReportDataSource(dataSourceName, dt)
rViewer.LocalReport.DataSources.Clear()
rViewer.LocalReport.DataSources.Add(ds)
rViewer.LocalReport.Refresh()
I have 2 approaches to bind data to ReportViewer control. Which one is better? Could you please give me some advice?
Approach 1: Using SqlDataAdapter
Dim dt As DataTable = New DataTable
Dim conn As SqlConnection = New SqlConnection(connString)
Try
conn.Open()
Dim cmd As New SqlCommand(sql, conn)
Dim adapter As New SqlDataAdapter(cmd)
adapter.Fill(dt)
Catch ex As Exception
Finally
conn.Close()
End Try
Dim ds As New ReportDataSource(dataSourceName, dt)
rViewer.LocalReport.DataSources.Clear()
rViewer.LocalReport.DataSources.Add(ds)
rViewer.LocalReport.Refresh()
Approach 2: Using SqlDataReader
Dim dt As New DataTable()
Dim conn As SqlConnection = New SqlConnection(connString)
Try
conn.Open()
Dim cmd As New SqlCommand(sql, conn)
Dim reader As SqlDataReader = cmd.ExecuteReader()
dt.Load(reader)
reader.Close()
Catch ex As Exception
Finally
conn.Close()
End Try
Dim ds As New ReportDataSource(dataSourceName, dt)
rViewer.LocalReport.DataSources.Clear()
rViewer.LocalReport.DataSources.Add(ds)
rViewer.LocalReport.Refresh()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我必须在两者之间进行选择,我会选择第一个,因为使用dataReader在内部填充数据集。
您的第二个示例转换数据集中的数据读取器。
第一个选项应该稍微快一些。
另一种选择是使用对象(实体)作为数据源。
您可以找到更多信息在这里。
If I have to choose between the two I would go for the first one cause a dataset is populated internally using a datareader.
Your second sample converts a datareader in a dataset.
The first option should be slightly faster.
Another option would be to use objects (entities) as datasource.
You can find more infos here.