กลับมาที่หน้า Windows Form จากนั้นให้ Click ที่ Button เพื่อสร้าง Event ในการโหลด Report โดยใส่คำสั่งดังนี้
Code VB.NET
Imports CrystalDecisions.CrystalReports.Engine
Imports System.Data.SqlClient
Public Class frmReport
Private Sub btnReport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReport.Click
Dim objConn As New SqlConnection
Dim objCmd As New SqlCommand
Dim dtAdapter As New SqlDataAdapter
Dim ds As New DataSet
Dim dt As DataTable
Dim strConnString, strSQL As String
strConnString = "Server=localhost;UID=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;"
strSQL = "SELECT * FROM audit WHERE CustomerID = '" & Me.txtCustomerID.Text & "' "
objConn.ConnectionString = strConnString
With objCmd
.Connection = objConn
.CommandText = strSQL
.CommandType = CommandType.Text
End With
dtAdapter.SelectCommand = objCmd
dtAdapter.Fill(ds, "myDataTable")
dt = ds.Tables(0)
dtAdapter = Nothing
objConn.Close()
objConn = Nothing
Dim rpt As New ReportDocument()
Dim directory As String = My.Application.Info.DirectoryPath
'rpt.Load(directory & "\myCrystalReport1.rpt")
rpt.Load("C:\DemoCrystalReport2\DemoCrystalReport2\myCrystalReport1.rpt")
rpt.SetDataSource(dt)
Me.CrystalReportViewer1.ReportSource = rpt
Me.CrystalReportViewer1.Refresh()
End Sub
End Class
Code C#
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using CrystalDecisions.CrystalReports.Engine;
using System.Data.SqlClient;
public class frmReport
{
private void btnReport_Click(System.Object sender, System.EventArgs e)
{
SqlConnection objConn = new SqlConnection();
SqlCommand objCmd = new SqlCommand();
SqlDataAdapter dtAdapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataTable dt = null;
string strConnString = null;
string strSQL = null;
strConnString = "Server=localhost;UID=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;";
strSQL = "SELECT * FROM audit WHERE CustomerID = '" + this.txtCustomerID.Text + "' ";
objConn.ConnectionString = strConnString;
var _with1 = objCmd;
_with1.Connection = objConn;
_with1.CommandText = strSQL;
_with1.CommandType = CommandType.Text;
dtAdapter.SelectCommand = objCmd;
dtAdapter.Fill(ds, "myDataTable");
dt = ds.Tables[0];
dtAdapter = null;
objConn.Close();
objConn = null;
ReportDocument rpt = new ReportDocument();
string directory = My.Application.Info.DirectoryPath;
//rpt.Load(directory & "\\myCrystalReport1.rpt")
rpt.Load("C:\\DemoCrystalReport2\\DemoCrystalReport2\\myCrystalReport1.rpt");
rpt.SetDataSource(dt);
this.CrystalReportViewer1.ReportSource = rpt;
this.CrystalReportViewer1.Refresh();
}
}
หลังจากวาง Code เรียบร้อยแล้ว ลองกดที่ Run เพื่อดูผลลัพธ์ของ Report