我通过以下任一代码在运行时将数据库连接到crystal报表,但它在回发中丢失了数据库连接(当我在treeview中单击或尝试导航到下一页时)
这是我得到的错误:
System.Runtime.InteropServices.COMException:数据库登录失败。
ReportDocument cryRpt = new ReportDocument();
cryRpt.Load(path);
(((1)))
for (int i = 0; i < cryRpt.DataSourceConnections.Count; i++)
cryRpt.DataSourceConnections[i].SetConnection(ServerName, DatabaseName, UserID, Password);
for (int i = 0; i < cryRpt.Subreports.Count; i++)
for (int j = 0; j < cryRpt.Subreports[i].DataSourceConnections.Count; j++)
cryRpt.OpenSubreport(cryRpt.Subreports[i].Name).DataSourceConnections[j].SetConnection(ServerName, DatabaseName, UserID, Password);
cryRpt.OpenSubreport(cryRpt.Subreports[i].Name).DataSourceConnections[j].SetConnection(ServerName, DatabaseName, UserID, Password);
(((2)))
crConnectionInfo.ServerName = ServerName;
crConnectionInfo.DatabaseName = DatabaseName;
crConnectionInfo.UserID = UserID;
crConnectionInfo.Password = Password;
crDatabase = cryRpt.Database;
crTables = crDatabase.Tables;
for (int i = 0; i < crTables.Count; i++)
{
crTable = crTables[i];
crTableLogOnInfo = crTable.LogOnInfo;
crTableLogOnInfo.ConnectionInfo = crConnectionInfo;
crTable.ApplyLogOnInfo(crTableLogOnInfo);
//crTable.Location = crConnectionInfo.DatabaseName + ".dbo." + crTable.Location.Substring(crTable.Location.LastIndexOf(".") + 1)
}
答案 0 :(得分:1)
回发时,CrystalReportViewer正在丢失具有有效连接的报告。
将我在会话中存储cryRpt的行添加到现有报告加载代码中。如下所示,将此组合代码放入仅在初始页面加载时运行的例程:
if (!IsPostBack)
{
// do all your normal code loading you did in your OP
// add this line to store the ReportDocument
Session["myReport"] = cryRpt;
crReportViewer.ReportSource = cryRpt;
crReportViewer.Show();
}
然后将此代码放在else中(当我们回发时)从会话中获取ReportDocument并将其重新分配给CrystalReportViewer控件。
else
{
// this is when you postback
// (i.e. paging, drilling into tree view, exporting, printing)
crReportViewer.ReportSource = (ReportDocument)Session["myReport"];
crReportViewer.Show();
}