Report asking for database login on setting DataTable as DataSource

跟風遠走 提交于 2019-11-28 14:46:00

Two things you need to focus on:

  1. You are connecting to same server and database name which were used to design the report.
  2. You are connecting to a different database or server.

Scenario 1: Same server and database name

In this case you need to provide the credentials using SetDatabaseLogon method as follows

'crDoc1 is your ReportDocument
'dtDataTable is your DataTable

'set database logon info
crDoc1.SetDatabaseLogon("db_user_name", "db_password", "db_server_name_or_ip", "database_name");

'set DataTable as DataSource
crDoc1.SetDataSource(dtDataTable)

Scenario 2: Different server OR database name

In this case you need to provide the credentials using ApplyLogOnInfo method

ConnectionInfo crConInfo = new ConnectionInfo();
TableLogOnInfo crTblLogonInfo = new TableLogOnInfo();

crConInfo.ServerName = "db_server_name_or_ip";
crConInfo.DatabaseName = "database_name";
crConInfo.UserID = "db_user_name";
crConInfo.Password = "db_password";  

'crDoc1 is your ReportDocument
'dtDataTable is your DataTable

'Set DataSource to your DataTable
crDoc1.SetDataSource(dtDataTable)

'after setting the DataSource apply Logon credentials to each table in ReportDocument
Tables CrTables = crDoc1.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables) {
    crTblLogonInfo = CrTable.LogOnInfo;
    crTblLogonInfo.ConnectionInfo = crConInfo;
    CrTable.ApplyLogOnInfo(crTblLogonInfo);
}
crDoc1.Refresh();
CrystalReportViewer1.ReportSource = crDoc1;

Notes: If you have any sub reports, you need to apply SetDatabaseLogon and/or ApplyLogOnInfo to all the sub reports and their tables respectively.

UPDATE:
Applying ApplyLogOnInfo to subreports

foreach (ReportDocument srSubReport in crDoc1.Subreports) {
    foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in srSubReport.Database.Tables) {
        crTblLogonInfo = CrTable.LogOnInfo;
        crTblLogonInfo.ConnectionInfo = crConInfo;
        CrTable.ApplyLogOnInfo(crTblLogonInfo);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!