接続の作成:
/// <summary>
/// Sets the connection.
/// </summary>
public void SetConnection()
{
_connection = new SqlConnection(Settings.Default.connectionString);
if (_connection.State == System.Data.ConnectionState.Open)
{
_connection.Close();
}
_connection.Open();
}
/// <summary>
/// Closes the connection.
/// </summary>
public void CloseConnection()
{
if (_connection.State == System.Data.ConnectionState.Open)
{
_connection.Close();
_connection.Dispose();
}
}
上記の接続を使用して、データセットを手動で入力するか、ソリューションにデータセットを追加して、接続コードを記述せずにデータを取得します。Employee.XSD を追加したとします。クエリとデータテーブルを自動生成することにより、データベースからデータを取得するのに役立つテーブルアダプターを XSD に追加します。これらすべてのことを行った後。プロジェクトのどこかにメソッドを作成し、
Public DataTable GetAllEmployees()
{
Employee.EmployeeTableAdapter adapt = New Employee.EmployeeTableAdapter();
DataTable dt = New DataTable();
dt = adapt.GetData(); // you can also use fill based on your criteria.
return dt; //your datatable with data
}
次に、フォームに reportviewer コントロールを追加します。
ReportViewer1 rpt = New ReportViewer();
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load("path of rpt file");
rptDoc.SetDataSource(GetAllEmployees());
rpt.Document = rptDoc;
rpt.Refresh();
その前に Crystal Report から、要件に従ってレポートにテーブルのフィールドを追加します。
達成するための別の方法
Crystal Reports は、さまざまなオブジェクトで使用できます。それを動的にバインドするシナリオがある場合は、以下の私の回答を参照してください。次に、新しいデータセットをソリューションに追加するという 1 つのことを行うことができます。データテーブルを作成し、適切なデータ型で必要な列を追加します。クエリまたはテーブル アダプターを追加しないでください。コードからクラス ファイルを追加し、データ テーブル列とまったく同じプロパティを作成します。データテーブルをレポートのソースとして設定し、その列をレポートに追加します。
For example , if you have columns
ID - integer
EmpName - string
Salary - double
Department - string
クラスを作成する
public class Employee
{
private SqlConnection _connection;
public int ID {get;set;}
public string EmpName {get;set;}
public double Salary {get;set;}
public string Department {get;set;}
/// <summary>
/// Sets the connection.
/// </summary>
public void SetConnection()
{
//assuming connection string is placed in settings file from Project Properties.
_connection = new SqlConnection(Settings.Default.connectionString);
if (_connection.State == System.Data.ConnectionState.Open)
{
_connection.Close();
}
_connection.Open();
}
/// <summary>
/// Closes the connection.
/// </summary>
public void CloseConnection()
{
if (_connection.State == System.Data.ConnectionState.Open)
{
_connection.Close();
_connection.Dispose();
}
}
public DataTable GetEmployees()
{
DataTable dt = new DataTable("Employee");
// using above connection
SetConnection();
using(SqlCommand command = new SqlCOmmand("commandText",_connection))
{
using(SqlDataReader reader = command.ExecuteReader())
{
dt.Load(reader);
}
}
return dt;
}
}
ここで、dtataset 内に作成されたデータテーブルにデータを入力する別の関数を作成します。
public void PopulateDataTable()
{
DataTable dt = GetEmployee();
Employee dsEmployee = New DataSet();
dsEmployee.EmployeeDataTable dtEmp = new dsEmployee.EmployeeDataTable();
dtEmp = dt;
}