Friday, March 12, 2010

C# Basic use of Reportviewer control

Using the reportviewer control is pretty simple. 1. Add a dataset object to your project that represents the data you will be displaying on your report. Make sure you take note of the name. 2. Add a report to the project, modify the report to display the data the way you want it. Use Datasources on the toolbar to add your previously created dataset to the report. 3. Drop a reportviewer control onto your aspx page, choose your report from the list of available reports for it to display. 4. In the code behind on the page load event add the following lines modifying them as necessary for your situation:

DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection cnConn = new SqlConnection(ConfigurationManager.ConnectionStrings["yourconfigname"].ConnectionString);
da.SelectCommand = new SqlCommand("SELECT * FROM yourtable", cnConn);
cnConn.Open();
da.Fill(dt);
cnConn.Close();
cnConn.Dispose();
//the "ds_dt" must match the name of your dataset used on the report.
ReportDataSource mRDS = new ReportDataSource("ds_dt", dt);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(mRDS);
ReportViewer1.DataBind();

You will notice that an objectdatasource will be added to the aspx when you select the report on the reportviewer control. You can remove the objectdatasource.

No comments: