在C# APS.net 使用DATASET 運行 Crystal Report

在C# APS.net  使用DATASET 運行 Crystal Report

1. 先建立一個只有資料行但沒有連結資料庫的DataSet 

 

2. 建立一個 Crystal Report 並使用ProjectData > ADO.NET DataSet 連接剛才新開的DataSet

3.新增一個webform 並加入BUTTON ,CrystalReportViewer,Textbox

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CrystalTest4.aspx.cs" Inherits="CrystalTest4" %>

<%@ Register Assembly="CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" Namespace="CrystalDecisions.Web" TagPrefix="CR" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
            <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" />
        </div>
        
    </form>
</body>
</html>

4. 在 .cs 加入以下代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrystalDecisions.CrystalReports.Engine;
using System.Data;
using System.Data.SqlClient;
using CrystalDecisions.Shared;
public partial class CrystalTest4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      

        ReportDocument rd = new ReportDocument();
        string reportPath = Server.MapPath("CrystalReport4.rpt");


        DataSet ds = InsertRecord();
        rd.Load(reportPath);

        rd.SetDataSource(ds);

        this.CrystalReportViewer1.ReportSource = rd;
     
    }
    private DataSet InsertRecord()
    {
        string constr = @"Data Source = 127.0.0.1; Initial Catalog = xxxx_DB; Persist Security Info = True; User ID = xxx_dbuser; Password =$xxxx";

        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("Select * from tbl_ole where ID='" + TextBox1.Text + "'"))

            {

                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        sda.Fill(ds, "DataTable1");
                        return ds;
                    }
                }


            }




        }



    }

    protected void Button1_Click(object sender, EventArgs e)
    {
       

        ReportDocument rd = new ReportDocument();
        string reportPath = Server.MapPath("CrystalReport4.rpt");

        
        DataSet ds = InsertRecord();
        rd.Load(reportPath);

        rd.SetDataSource(ds);
       
        this.CrystalReportViewer1.ReportSource = rd;
     
    }
}

5. 在textbox 輸入ID 及按BUTTON, 就可出現所選資料