在WPF表单中将项目添加到泛型列表中
本文关键字:泛型 列表 添加 WPF 表单 项目 | 更新日期: 2023-09-27 18:07:04
我有一个名为employeeList的列表,我正在用一个数据表填充它,它正在正常工作。因此,现在我希望能够在运行时向列表中添加(可选)项。我想到了一个简单的清单。插入会工作,但我得到错误,当我尝试这样做。我遇到问题的行是employeeList。插入,两个错误包含在代码块中。
private static List<Employee> employeeList(string store,
string loginId = "",
int position = 100)
{
var employeeList = default(List<Employee>);
employeeList = new List<Employee>();
using (var dt = Logins.getDataset(store, "Manpower_SelectLogins"))
{
foreach (DataRow dr in dt.Rows)
{
employeeList.Add(new Employee(dr["LoginId"].ToString()));
}
}
if (string.IsNullOrEmpty(loginId) != true)
{
employeeList.Insert(position, loginId);
//Error 2 Argument 2: cannot convert from 'string' to
//'ManpowerManager.MainWindow.Employee
//Error 1 The best overloaded method match for
//'System.Collections.Generic.List<ManpowerManager.MainWindow.Employee>.
//Insert(int, ManpowerManager.MainWindow.Employee)' has some invalid arguments
}
return employeeList;
}
我做错了什么?
employeeList
是ManpowerManager.MainWindow.Employe
类型的列表,因此您不能在其中插入字符串。
我想你可能需要这样的东西:
employeeList.Insert(position, new Employee(loginId));
您需要插入一个新的Employee:
employeeList.Insert(position, new Employee(loginid)
{
FirstName = "steve", // or whatever you want to initalize (or not)
} );
您正在尝试将字符串插入Employee对象列表,因此您的错误。
作为旁白,您正在分配null (default(List<Employee>)
),然后在下一行,分配一个新列表。您可以在一行中完成:List<Employee> employeeList = new List<Employee>();