Configuring the ReportViewer control at run time

July 09, 2007

I’ve been using the ReportViewer .NET control recently for a project at work. I’m using a collection of data objects as a data source, and while the ReportViewer itself works great, the documentation doesn’t really go beyond putting things together in the Visual Studio designer. It’s actually just as easy to do the configuration in code at run time, which is useful if you need to choose from multiple reports or types of data. Just add the ReportViewer control in the designer, but use the following code example instead of choosing a report and bindings context.

string dataSetName = "MyApplication_ModelObject";
string resourcePath = "MyApplication.SomeReport.rdlc"
List<modelObject> dataSource = ObjectProvider.GetObjects();

reportViewer.LocalReport.ReportEmbeddedResource = resourcePath;
reportViewer.LocalReport.DataSources.Add( new ReportDataSource( dataSetName, dataSource ) );
this.reportViewer.RefreshReport();

Note that the ReportEmbeddedResource string must include the full namespace as well as the file name. If you’re not sure what data set name to use, just open your report in the XML viewer.

Marc Charbonneau is a mobile software engineer in Portland, OR. Want to reply to this article? Get in touch on Twitter @mbcharbonneau.