Thursday, August 28, 2008

View Reporting Service in ReportViewer

ConnectionStringSettings lSetting;
lSetting = ConfigurationManager.ConnectionStrings["Billing.Connection"];

//string cnString = @"Data Source= HTS-003\SQL2005;Initial Catalog=Billing;" +
// "User Id=sa;Password=hts";

//use following if you use standard security
//string cnString = @"Data Source=(local);Initial Catalog=northwind;
// Integrated Security=SSPI";

//declare Connection, command and other related objects
SqlConnection conReport = new SqlConnection();
SqlCommand cmdReport = new SqlCommand();
SqlDataReader drReport;
DataSet dsReport = new PatientDataSet();//Datasource Name

try
{
//open connection
conReport.ConnectionString = lSetting.ConnectionString;
conReport.Open();
//prepare connection object to get the data through reader and populate into dataset
cmdReport.CommandType = CommandType.Text;
cmdReport.Connection = conReport;
cmdReport.CommandText = "Select * FROM BA_Patients ";

//read data from command object
drReport = cmdReport.ExecuteReader();

//new cool thing with ADO.NET... load data directly from reader to dataset
dsReport.Tables[0].Load(drReport);

//close reader and connection
drReport.Close();
conReport.Close();

//provide local report information to viewer
reportViewer1.LocalReport.ReportEmbeddedResource = "BillingAndAccounts.PatientList.rdlc";

//prepare report data source
ReportDataSource rds = new ReportDataSource();
rds.Name = "PatientDataSet_BA_Patients";
rds.Value = dsReport.Tables[0];
reportViewer1.LocalReport.DataSources.Add(rds);

//add report parameters
ReportParameter[] Param = new ReportParameter[2];

switch (reportType)
{
case "N":
Param[0] = new ReportParameter("parReportTitle", "Orders by Nationality");
Param[1] = new ReportParameter("parReportType", "N");
break;
case "T":
Param[0] = new ReportParameter("parReportTitle", "Orders List");
Param[1] = new ReportParameter("parReportType", "T");
break;
case "S":
Param[0] = new ReportParameter("parReportTitle", "Orders by Sex");
Param[1] = new ReportParameter("parReportType", "S");
break;
case "O":
Param[0] = new ReportParameter("parReportTitle", "Orders by Occupation");
Param[1] = new ReportParameter("parReportType", "O");
break;
case "P":
Param[0] = new ReportParameter("parReportTitle", "Orders by PatientName");
Param[1] = new ReportParameter("parReportType", "P");
break;
}

reportViewer1.LocalReport.SetParameters(Param);

//load report viewer
reportViewer1.RefreshReport();
}
catch (Exception ex)
{
//display generic error message back to user
MessageBox.Show(ex.Message);
}
finally
{
//check if connection is still open then attempt to close it
if (conReport.State == ConnectionState.Open)
{
conReport.Close();
}
}

No comments: