Hi ishuhasan21,
Note: For this sample i have used below Articles. For more details refer below Article link.
Basic Crystal Report Tutorial with example in Windows Forms (WinForms) Application using C# and VB.Net
Please refer below sample.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Default(Form1)
Code
C#
private void View_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.Show();
}
VB.Net
Private Sub View_Click(ByVal sender As Object, ByVal e As EventArgs) Handles View.Click
Dim frm As Form2 = New Form2()
frm.Show()
End Sub
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using CrystalDecisions.CrystalReports.Engine;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports CrystalDecisions.CrystalReports.Engine
Home(Form2)
Code
C#
private void Form2_Load(object sender, EventArgs e)
{
ReportDocument crystalReport = new ReportDocument();
crystalReport.Load(Application.StartupPath.Replace("bin\\Debug", "") + "CrystalReport1.rpt");
Customers dsCustomers = this.GetData("SELECT TOP 20 * FROM Customers");
crystalReport.SetDataSource(dsCustomers);
this.crystalReportViewer1.ReportSource = crystalReport;
}
private Customers GetData(string Query)
{
string constr = @"Data Source=.\SQL2019;Initial Catalog=Northwind;UID=sa;PWD=pass@123";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(Query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (Customers dsCustomers = new Customers())
{
sda.Fill(dsCustomers, "Customers");
return dsCustomers;
}
}
}
}
}
VB.Net
Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim crystalReport As ReportDocument = New ReportDocument()
crystalReport.Load(Application.StartupPath.Replace("bin\Debug", "") & "CrystalReport1.rpt")
Dim dsCustomers As Customers = Me.GetData("SELECT TOP 20 * FROM Customers")
crystalReport.SetDataSource(dsCustomers)
Me.CrystalReportViewer1.ReportSource = crystalReport
Me.CrystalReportViewer1.RefreshReport()
End Sub
Private Function GetData(ByVal Query As String) As Customers
Dim constr As String = "Data Source=.\SQL2019;Initial Catalog=Northwind;UID=sa;PWD=pass@123"
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(Query)
Using sda As SqlDataAdapter = New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dsCustomers As Customers = New Customers()
sda.Fill(dsCustomers, "Customers")
Return dsCustomers
End Using
End Using
End Using
End Using
End Function
Screenshot