29 ธันวาคม 2559

Pass Parameter and Formula to Crystal Report (Vb.net) Without Messagebox Resolve

'Tip: Move   rpt.SetParameterValue("ParamTitle", txtParameterTitle.Text) and rpt.DataDefinition.FormulaFields("Formula Title").Text = "'" & txtFormulaFields.Text & "'" After rpt.SetDataSource(dt)
-------------------------------------------------------------------------------------------




Imports CrystalDecisions.CrystalReports.Engine

Public Class Form1



    '*** TableRows (DataTable) ***'
    Function DataTableRows() As DataTable
        Dim dt As New DataTable
        Dim dr As DataRow

        '*** Column ***'
        dt.Columns.Add("id")
        dt.Columns.Add("ProductName")
        dt.Columns.Add("Units")
        dt.Columns.Add("Prices", GetType(System.Int64))
        'หากลืมใช้ GetType ให้ใช้โค้ดด้านล่างก็ได้
        'dt.Columns("Prices").DataType = System.Type.GetType("System.Int64")

        '*** Rows ***'
        dr = dt.NewRow
        dr("id") = "001"
        dr("ProductName") = "Printer Name 001"
        dr("Units") = "Box"
        dr("Prices") = "115"

        dt.Rows.Add(dr)

        '*** Rows ***'
        dr = dt.NewRow
        dr("id") = "C002"
        dr("ProductName") = "Keyboard "
        dr("Units") = "Box"
        dr("Prices") = "21"
        dt.Rows.Add(dr)

        '*** Rows ***'
        dr = dt.NewRow
        dr("id") = "C003"
        dr("ProductName") = "Mouse"
        dr("Units") = "Box"
        dr("Prices") = "6543"
        dt.Rows.Add(dr)

  

        Return dt '*** Return DataTable ***'




    End Function

    Private Sub btnViewReport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnViewReport.Click
        Dim dt As DataTable
        dt = DataTableRows()

        Dim rpt As New ReportDocument()
        Dim directory As String = My.Application.Info.DirectoryPath
        'rpt.ReuseReportParametersOnRefresh = False
        'rpt.Load(directory & "..\..\myCrystalReport.rpt")
        rpt.Load("..\..\CrystalReport1.rpt")


        rpt.SetDataSource(dt)
        rpt.SetParameterValue("ParamTitle", txtParameterTitle.Text)

        'การส่งค่า Formula Fields ต้องมีเครื่องหมาย   ' ภายในเสมอ (ใน Crystal Report เป็น X+1 Formula Fields)
        rpt.DataDefinition.FormulaFields("Formula Title").Text = "'" & txtFormulaFields.Text & "'"

        Form2.CrystalReportViewer1.ReportSource = rpt
        Form2.CrystalReportViewer1.Refresh()
        Form2.StartPosition = FormStartPosition.CenterScreen
        Form2.WindowState = FormWindowState.Maximized
        Form2.ShowDialog()

    End Sub
End Class