在C#中在运行时更改Crystal Report数据源(访问)

时间:2015-04-13 09:35:39

标签: c# winforms ms-access crystal-reports

我收到错误'登录失败'在尝试在运行时更改我的数据源时。我已经搜索了SO和SAP网站,并从中汇总了下面的代码,但我仍然得到了错误。我的访问数据库是2013年,并且没有密码保护,我使用默认的" Admin"用户。该报告具有OLE DB连接。我的代码循环遍历所有表,包括子报表并更改登录,我还更改了数据库登录。任何帮助非常感谢:

public void RunTestReport()
    {
        DataSet testDataSet = new DL.NonConformance().GetNonConformances(1, "NonConformance");

        var rpt = new ReportDocument();
        rpt.Load(@"C:\Reports\rptTest.rpt");

        SetCrystalLogin(rpt);

        rpt.SetDataSource(testDataSet);

        crystalReportViewer1.ReportSource = rpt;
        crystalReportViewer1.Refresh();
    }

    public void SetCrystalLogin(ReportDocument oRpt)
    {
        ConnectionInfo oConnectInfo = new ConnectionInfo();

        string dbpath = string.Concat(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"\db\dbacc.db");

        oConnectInfo.ServerName = dbpath;
        oConnectInfo.DatabaseName = string.Empty;
        oConnectInfo.UserID = "Admin";
        oConnectInfo.Password = string.Empty;

        // Set the logon credentials for all tables
        SetCrystalTablesLogin(oConnectInfo, oRpt.Database.Tables);

        // Check for subreports
        foreach (CrystalDecisions.CrystalReports.Engine.Section oSection in oRpt.ReportDefinition.Sections)
        {
            foreach (CrystalDecisions.CrystalReports.Engine.ReportObject oRptObj in oSection.ReportObjects)
            {
                if (oRptObj.Kind == CrystalDecisions.Shared.ReportObjectKind.SubreportObject)
                {
                    // This is a subreport so set the logon credentials for this report's tables
                    CrystalDecisions.CrystalReports.Engine.SubreportObject oSubRptObj = oRptObj as CrystalDecisions.CrystalReports.Engine.SubreportObject;

                    // Open the subreport
                    CrystalDecisions.CrystalReports.Engine.ReportDocument oSubRpt = oSubRptObj.OpenSubreport(oSubRptObj.SubreportName);

                    SetCrystalTablesLogin(oConnectInfo, oSubRpt.Database.Tables);
                }
            }
        }

        oRpt.Refresh();

        oRpt.SetDatabaseLogon("Admin", string.Empty, dbpath, string.Empty, true);

        oRpt.VerifyDatabase();

        oRpt.Refresh();
    }

    private void SetCrystalTablesLogin(CrystalDecisions.Shared.ConnectionInfo oConnectInfo, Tables oTables)
    {
        foreach (CrystalDecisions.CrystalReports.Engine.Table oTable in oTables)
        {
            CrystalDecisions.Shared.TableLogOnInfo oLogonInfo = oTable.LogOnInfo;
            oLogonInfo.ConnectionInfo = oConnectInfo;

            oTable.ApplyLogOnInfo(oLogonInfo);
        }
    }

1 个答案:

答案 0 :(得分:0)

事实证明你无法在运行时配置.accdb数据源,我需要创建一个ODBC连接。