Ref:
HTML
<form id="form1" runat="server">
Please Select Year
<asp:DropDownList ID="ddlYears" runat="server" OnSelectedIndexChanged="OnSelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="1996" Value="1996" />
<asp:ListItem Text="1997" Value="1997" />
<asp:ListItem Text="1998" Value="1998" />
</asp:DropDownList>
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" />
</form>
Namespaces
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using CrystalDecisions.CrystalReports.Engine;
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindCrystalReport();
}
}
private void BindCrystalReport()
{
ReportDocument crystalReport = new ReportDocument();
crystalReport.Load(Server.MapPath("~/CustomerReport.rpt"));
Customers dsCustomers = GetData(@"SELECT * FROM Customers customers
INNER JOIN Orders orders ON customers.CustomerId = orders.CustomerId
WHERE DATEPART(YEAR,orders.OrderDate) = @Years");
crystalReport.SetDataSource(dsCustomers);
CrystalReportViewer1.ReportSource = crystalReport;
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
BindCrystalReport();
}
private Customers GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Years", this.ddlYears.SelectedItem.Value);
sda.SelectCommand = cmd;
using (Customers dsCustomers = new Customers())
{
sda.Fill(dsCustomers, "DataTable1");
return dsCustomers;
}
}
}
}
Screenshot
