How to display data in crystal report using 2 sql request and 2 datatables in dataset?

99封情书 提交于 2019-12-02 14:17:46

问题


I have a dataset with 2 datatable aand I need to use 2 sql request to display data in crystal report. So I create 2 datatable in my dataset (DataTable1 and dataTable2) I tried this code but it always execute the second sql request!!

con.ConnectionString = @"connection";

string sql = "MyRequest1";
string sql1 = "MyRequest2";

DataSet1 ds = new DataSet1();  

SqlDataAdapter dad = new SqlDataAdapter(sql, con);
SqlDataAdapter dad1 = new SqlDataAdapter(sql1, con);

dad.Fill(ds.Tables["DataTable1"]);
dad1.Fill(ds.Tables["DataTable2"]);

CrystalReport1 report = new CrystalReport1();

report.SetDataSource(ds.Tables["DataTable2"]);
report.SetDataSource(ds.Tables["DataTable1"]);

crystalReportViewer1.ReportSource = report;

crystalReportViewer1.Refresh();

回答1:


You would need to merge the datatables into one and set them. Every time you invoke SetDataSource with a datatable, you are overriding the previous data.

Use the Merge() functionality to achieve this -

DataTable dt = ds.Tables["DataTable2"];
DataTable dt2 = ds.Tables["DataTable1"];
dt.Merge(dt2);
report.SetDataSource(dt);



回答2:


the solution is to implement a Datatable Method for each DataTable used in the Dataset: example for the 1st Datatable:

protected DataTable DataTable1()
    {
        string sql = "MyRequest";
        SqlDataAdapter dad = new SqlDataAdapter(sql, con);
        DataSet1 ds = new DataSet1();
        dad.Fill(ds.Tables["NameOfDataTable"]);
        DataTable dt = ds.Tables["NameOfDataTable"];
        return dt;

    }

and in the print button you add this code:

try {
            DataSet ds = new DataSet();
            DataTable dt1 = DataTable1().Copy(); //the name of the method
            ds.Tables.Add(dt1);
            CrystalReport1 myreport = new CrystalReport1();
            myreport.SetDataSource(ds);
            crystalReportViewer1.ReportSource = myreport;

}
catch (Exception ex)
{
   //code ...
}

It works successfully :)



来源:https://stackoverflow.com/questions/29797382/how-to-display-data-in-crystal-report-using-2-sql-request-and-2-datatables-in-da

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!