Drawing Chart With C#

Hello, now i want to show how to draw a chart with C# in a RDLC report.
This tutorial is using an Access Database, but you can use SQL Server with minimal changes.
Design a Data Table like:

Too is need design a DataSet (In Visual Studio) like the Access Data Table:

Now Create a RDLC Report using the DataSet how Data Source:

Add the Chart control to the RDLC Report:

Select the Chart Type (Line Chart to this example):

Design the Form to display the report addign a ReportViewer control:

Configure the Report to Display the Series (Usethe mouse):

The code to Display the Data:
string CnnStr = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;" +
    "Data Source={0};" +
    "Persist Security Info=False",
    "D:\\DOCS\\tyrodeveloper\\Blogger\\BlogPubCSharp\\BlogPubCSharp.accdb");
string RptFileName = "D:\\DOCS\\tyrodeveloper\\Blogger\\"+
    "BlogPubCSharp\\BlogPubCSharp\\Reports\\rptSalesLineChart.rdlc";
string DataSetName = "dsRptSalesChart";//Like the RDLC
OleDbConnection cnnReport = new OleDbConnection(CnnStr);
try {
    if (!File.Exists(RptFileName)){
        MessageBox.Show(String.Format("File not found {0}", RptFileName),
            "System Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }
    DataSet dsReport = new DataSet(); 
    cnnReport.Open();
    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = cnnReport;
    cmd.CommandText = 
        "SELECT SALE_DATE,SUM(TOTAL) AS TOTAL " +
        " FROM SALE " +
        " WHERE YEAR(SALE_DATE)=@YEAR " +
        " AND MONTH(SALE_DATE) =@MONT " +
        " GROUP BY SALE_DATE";
    cmd.Parameters.Add("@YEAR", 
        OleDbType.Integer).Value = txtYear.Text;
    cmd.Parameters.Add("@MONTH", 
        OleDbType.Integer).Value = txtMonth.Text;
    OleDbDataAdapter daReporte =
        new OleDbDataAdapter(cmd);
    daReporte.Fill(dsReport, DataSetName);
    daReporte.Dispose();
    cnnReport.Dispose();

    if (dsReport.Tables[DataSetName].Rows.Count == 0) {
        cnnReport.Close();
        MessageBox.Show("No data", "System Information",
            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        return;
    }
    reportViewer1.LocalReport.DataSources.Clear();
    reportViewer1.LocalReport.Dispose();
    reportViewer1.Reset();
    reportViewer1.LocalReport.DataSources.
        Add(new ReportDataSource(DataSetName, 
            dsReport.Tables[DataSetName]));
    reportViewer1.LocalReport.ReportPath = RptFileName;
    reportViewer1.RefreshReport();
}
catch (Exception ex){
    MessageBox.Show(ex.Message + "\n" + ex.StackTrace, 
        "System Information", MessageBoxButtons.OK, 
        MessageBoxIcon.Error);
}
finally { cnnReport.Close(); }

Demo of the Report

I have this information on the table:

The Report:

No hay comentarios:

Publicar un comentario