C# 使用DAL-BLL的Windows窗体
我的雇员是B班的 使用制度; 使用System.Collections.Generic; 使用System.Linq; 使用系统文本; 使用System.Data.SqlClient; 使用系统数据 名称空间测试 { 公共类雇员 { 私有字符串连接字符串C# 使用DAL-BLL的Windows窗体,c#,winforms,data-access-layer,C#,Winforms,Data Access Layer,我的雇员是B班的 使用制度; 使用System.Collections.Generic; 使用System.Linq; 使用系统文本; 使用System.Data.SqlClient; 使用系统数据 名称空间测试 { 公共类雇员 { 私有字符串连接字符串 public EmployeeDB() { //my connectionstring info } public int CountEmployees() { SqlC
public EmployeeDB()
{
//my connectionstring info
}
public int CountEmployees()
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("CountEmployees", con);
cmd.CommandType = CommandType.StoredProcedure;
try
{
con.Open();
return (int)cmd.ExecuteScalar();
}
catch (SqlException err)
{
// Replace the error with something less specific.
// You could also log the error now.
throw new ApplicationException("Data error.");
}
finally
{
con.Close();
}
}
public List<EmployeeDetails> GetEmployees()
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("GetAllEmployees", con);
cmd.CommandType = CommandType.StoredProcedure;
// Create a collection for all the employee records.
List<EmployeeDetails> employees = new List<EmployeeDetails>();
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
EmployeeDetails emp = new EmployeeDetails(
(int)reader["EmployeeID"], (string)reader["FirstName"],
(string)reader["LastName"], (string)reader["TitleOfCourtesy"]);
employees.Add(emp);
}
reader.Close();
return employees;
}
catch (SqlException err)
{
// Replace the error with something less specific.
// You could also log the error now.
throw new ApplicationException("Data error.");
}
finally
{
con.Close();
}
}
}
然后我构建类库并将引用添加到我的windows窗体项目中
这里是我的主窗体的屏幕截图,该类显示出来,但是没有方法。
要绑定到数据网格:
public interface IDataOperation
{
List<Employee> GetEmployees();
}
public class DataOperation : IDataOperation
{
public List<Employee> GetEmployees(){}
}
或者,只需通过编程方式将DataGrid的DataSource属性设置为GetEmployees()的结果,而无需使用BindingSource:
dataGrid.DataSource = dataOperation.GetEmployees();
编辑:在屏幕截图中,您应该在使用EmployeeDB之前实例化它,如下面的代码所示:
Test.EmployeeDB employeeDB = new Test.EmployeeDB();
dataGrid.DataSource = employeeDB.GetEmployees(); // assuming you have a dataGrid control
即使我添加了对我的DLL的引用,并且我的所有类都是公共的,但我键入bll时我的方法不会公开有什么原因吗?没有显示任何内容,有。如果您的DataOperation从接口继承,并且该接口没有声明约定列表GetEmployees(),则隐式强制转换您的DataOperation时(例如,IDataOperation dataOperation=new dataOperation()),除非您强制转换dataOperation并执行如下操作:((dataOperation)dataOperation).GetEmployees(),否则不会看到方法GetEmployees();谢谢您的帮助。从我收集的信息来看,似乎我缺少了接口类。windows窗体需要这样做才能像asp.net webforms那样公开DLL的方法吗?事实并非如此?但一旦我添加了接口类,我的方法就在那里了。@Tim您可以不用它,但使用接口来防止tig是一种很好的做法你的应用程序中的ht耦合。我可能必须打开一个新的问题,因为就我的一生而言,我无法理解为什么我的设计不允许我显示方法。我将编辑此问题,以在几分钟内向你显示我的确切类,如果你可以检查,如果我不理解。谢谢
dataGrid.DataSource = dataOperation.GetEmployees();
Test.EmployeeDB employeeDB = new Test.EmployeeDB();
dataGrid.DataSource = employeeDB.GetEmployees(); // assuming you have a dataGrid control