Let's say you just created a really cool Report for the .NET 2.0 ReportViewer Control (well, as cool as a report can be anyway).
But wait... At runtime, you want to examine and maybe even change attributes of the report. Like column names, labels, etc.
How do we get at Report properties at runtime?
One way is to tweak the RDLC (Client Report Definition) file before it is fed to the ReportViewer Control. RDLC is based on XML, so we can use XPath queries to find and tweak RDLC properties.
There is a post here that describes this method, and another example below.
First we create a utility function to load in the RDLC and tweak or examine it as necessary...
private TextReader GetCustomRDLC(string rdlcSource)
{
TextReader readerReport;
XmlDocument xmlReport = new XmlDocument();
Stream streamReport;
streamReport = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(rdlcSource);
xmlReport.Load(streamReport);
XmlNamespaceManager nsManager = new XmlNamespaceManager(xmlReport.NameTable);
nsManager.AddNamespace("dns", "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition");
XmlNodeList nodes = xmlReport.SelectNodes("//dns:Table[@Name='table1']//dns:Details//dns:Textbox", nsManager);
foreach (XmlNode node in nodes)
{
System.Diagnostics.Debug.WriteLine(node.Attributes["Name"].Value);
}
return new StringReader(xmlReport.OuterXml);
}
... then we can use this function to feed the ReportViewer Control...
// create a datasource for the report and set to the datatable dt1
ReportDataSource rds = new ReportDataSource();
rds.Name = "DataSet2_Employees";
dt1.DefaultView.Sort = "FirstName";
rds.Value = dt1.DefaultView;
reportViewer1.LocalReport.DataSources.Clear();
reportViewer1.LocalReport.DataSources.Add(rds);
reportViewer1.LocalReport.LoadReportDefinition(GetCustomRDLC("ReportViewerTest.Report2.rdlc"));
reportViewer1.RefreshReport();