VB.NET中ReportViewer使用ComboBox筛选数据出现重复记录问题
问题修复方案
根本原因
DataAdapter.Fill() 方法默认采用追加模式向目标DataTable写入数据,你代码中仅清空了ReportViewer的数据源,没有清空ds.Tables("dtLoins")中缓存的上一次查询结果,第二次查询后新旧数据合并,就出现了同时展示两次筛选结果的问题。
修复代码
你只需要在调用adapter.Fill之前,先清空目标DataTable的内容即可,同时建议优化为参数化查询避免SQL注入风险:
Sub GetReport() Dim rpt As New ReportDataSource Try ' 清空ReportViewer数据源 ReportViewer1.LocalReport.DataSources.Clear() ' 新增:清空DataTable的旧数据,解决数据叠加问题 If ds.Tables.Contains("dtLoins") Then ds.Tables("dtLoins").Clear() End If conn.openOcean() Catch ex As MySqlException MsgBox(ex.Message) End Try ' 优化为参数化查询,避免SQL注入 Dim cmd As New MySqlCommand("SELECT * FROM loins WHERE projectcode= @projectCode ORDER BY code ASC", conn.getConnection) cmd.Parameters.AddWithValue("@projectCode", ComboBox1.Text) adapter.SelectCommand = cmd adapter.Fill(ds.Tables("dtLoins")) rpt = New ReportDataSource("DataSet1", ds.Tables("dtLoins")) ReportViewer1.LocalReport.DataSources.Add(rpt) ReportViewer1.SetDisplayMode(Microsoft.Reporting.WinForms.DisplayMode.PrintLayout) ReportViewer1.ZoomMode = ZoomMode.Percent ReportViewer1.RefreshReport() End Sub
效果验证
修改后每次筛选都会先清空上一次的缓存数据,报表只会展示当前ComboBox选中值对应的查询结果。
内容的提问来源于stack exchange,提问作者Abd Domingos
相关产品推荐
相关产品推荐

