Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically set data source for ASP.NET ReportViewer control?

How do I programmatically set the data source for the ASP.NET ReportViewer control?

I have a VS 2008 ReportViewer control and want to switch between a couple of different reports.

I can switch reports by setting the report source and refreshing the control, but I can't see where to set the data source.

Each report has its own data source, and if I configure them initially when the control is built it is fine, but I need to switch between them.

like image 478
Maestro1024 Avatar asked Feb 15 '10 01:02

Maestro1024


2 Answers

I assume the question is about ReportViewer control.

reportViewer.LocalReport.DataSources.Clear();
reportViewer.LocalReport.DataSources.Add(new ReportDataSource("dsname", source));

"dsname" is the name of the data source, you can find it .rdlc file. source is the variable with data you want to show in the report.

like image 182
Alex Shirshov Avatar answered Oct 23 '22 11:10

Alex Shirshov


1) Basic markup:

<asp:ScriptManager ID="ScriptManager1" runat="server" />
<rsweb:ReportViewer ID="rptView" Width="1000px" ProcessingMode="Local"
        Font-Names="Verdana" Font-Size="8pt" InteractiveDeviceInfos="(Collection)" 
        WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt" runat="server"  >
</rsweb:ReportViewer>

2) Edit the report XML. Set up your dataset & field names:

<DataSets>
  <DataSet Name="dsSource">
    <Fields>
      <Field Name="MyField1">
        <DataField>MyField1</DataField>
        <rd:TypeName>System.String</rd:TypeName>
      </Field>
    <Query>
      <DataSourceName>dsSource</DataSourceName>
      <CommandText>/* Local Query */</CommandText>
    </Query>
  </DataSet>
</DataSets>

3) Set datasource on both report & report viewer (don't know why...both are necessary)

SqlConnection cn = new SqlConnection(_connectionString);
SqlCommand cmd = new SqlCommand("dbo.MyProc", cn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable tbl = new DataTable();

cn.Open();
da.Fill(tbl);
cn.Close();

rptView.Visible = true;
rptView.LocalReport.DataSources.Clear();
ReportDataSource rptData = new ReportDataSource("dsSource", tbl);

LocalReport r = new LocalReport();
r.ReportPath = Server.MapPath("~/Reports/MyReport.rdlc");
r.DataSources.Add(rptData);

rptView.LocalReport.DataSources.Add(rptData);
rptView.LocalReport.ReportPath = Server.MapPath("~/Reports/MyReport.rdlc");
rptView.LocalReport.Refresh();
like image 1
Brett Avatar answered Oct 23 '22 10:10

Brett