【问题标题】:Convert Data Grid View to Report Viewer将数据网格视图转换为报表查看器
【发布时间】:2015-12-08 23:45:56
【问题描述】:

绅士,

在我构建这个问题之前,我阅读了 30 多个搜索条目(并全部尝试了),其中大部分都没有回复。虽然这是我第一次在这里提问,但 10 多年来,这里一直是我最喜欢得到答案的地方。所以这里开始......我创建了以下代码来接受来自另一个页面上我的数据集的数据并将其传播到报表查看器中。

    //Creates the Grid View
        dataGridViewReport.DataSource = null;            
        dataGridViewReport.DataSource = ds.Tables[0].DefaultView;

        //Creates the Report
        reportViewer1.LocalReport.DataSources.Clear();
        this.reportViewer1.LocalReport.ReportPath = Application.StartupPath + @" \Report1.rdlc";// @"C:\Users\Pat\Documents\Visual Studio 2010\Projects\TTW 151200\TTW\Report1.rdlc";
        DataTable dt = ds.Tables[0];
        dt.TableName = "DataSet1";
        ReportDataSource rds = new ReportDataSource("DataSet1", dataGridViewReport.DataSource);
        reportViewer1.LocalReport.DataSources.Add(rds);            
        reportViewer1.RefreshReport();

当页面加载时,此页面从构造函数接受数据集值并在上面的代码中使用它。到目前为止,这一直是一场磨难,但我认为这可能很接近。我认为问题可能是找不到报告文件,尽管它不再抛出该错误。现在,当我创建报告文件 (Report1.rdlc) 时,它与其他表单文件一起出现。我以为我读到的是,它会在运行时位于 /bin 或 /release 文件夹中,但它似乎不存在,我也无法将其复制到该位置。我找不到实际路径在哪里,只有它没有运行时的路径。所以......首先,我不确定我是否有正确的代码来创建报告,但它不再抛出任何错误。视图显示只是说它找不到这个文件。其次,我应该指向哪里,以便此代码(或任何代码)具有文件的正确路径,以便可以创建报告。最后,我不明白需要数据集名称的参数,所以我只是从我发现的一些示例中复制了一些应该有效的代码。我将 Build Action 更改为 Embedded Resource 并将 Copy the Copy To Output 更改为 Copy Always 在属性表中(尽管它从未对我有用)。请帮忙。一个简单、清晰的代码 sn-p 将大大帮助我恢复理智!谢谢!

【问题讨论】:

    标签: c# sql-server datagridview reportviewer


    【解决方案1】:

    使用 setup 安装应用程序后,将 ReportPath 设置为 Application.StartupPath + <report name>(最好使用 Path.Combine insted 字符串连接)可能是正确的。

    但是在调试过程中你必须考虑到:

    • 编译后的文件(exedll等)在bin文件夹中(binbin\Debugbin\Release
    • rdlc 文件保留在您的原始项目文件夹中

    所以你可以实现一个函数来做这样的事情(对不起 VB.NET 代码):

    Private Function strRdlcFilePath(ByVal strRdlcFile As String) As String
    
        If Debugger.IsAttached And IO.File.Exists(IO.Path.Combine("<path to your project folder>", strRdlcFile)) Then
            strRdlcFilePath = IO.Path.Combine("<path to your project folder>", strRdlcFile)
        ElseIf Not Debugger.IsAttached And IO.File.Exists(IO.Path.Combine(Application.StartupPath, strRdlcFile)) Then
            strRdlcFilePath = IO.Path.Combine(Application.StartupPath, strRdlcFile)
        Else
            'worst case: use an OpenFileDialog to manually select your rdlc file
            strRdlcFilePath = "YourOpenFileDialog.FileName"
        End If
    
    End Function
    

    为了将ReportPath设置为:

    reportViewer1.LocalReport.ReportPath = strRdlcFilePath("Report1.rdlc")
    

    关于数据集问题,我认为您的代码是正确的,但之前声明了 DataTable,最好使用:

    ReportDataSource rds = new ReportDataSource(dt.TableName, dt);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 2013-12-10
      • 2018-05-11
      • 1970-01-01
      • 2017-12-29
      • 1970-01-01
      相关资源
      最近更新 更多