创建连接:
/// <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 中添加一个 tableadapter,它将通过自动生成查询和数据表来帮助您从数据库中提取数据。在做了所有这些事情之后。在项目的某处创建一个方法,
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 可用于各种对象。如果您有动态绑定它的方案,请参阅下面的答案然后您可以做一件事,即向解决方案添加一个新数据集。创建一个数据表并添加具有适当数据类型的所需列。不要添加查询或表适配器。现在从您的代码中添加一个类文件并创建与数据表列完全相同的属性。现在将数据表设置为报告源并将其列添加到报告中。
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;
}