Adding an item to a Generic List in WPF form
I have a list named employeeList that I am filling with a datatable, which is working correctly. So now I want to the ability to add an (optional) item to the list at runtime. I thought a simple List.Insert would work but I am getting errors when I try to do it. The line I having issues with is the employeeList.Insert and the two errors are included in the code block.
private static List<Employee> employeeList(string store,
string loginId = "",
int position = 100)
{
var employeeList = default(List<Employee>);
employeeList = new List<Employee>();开发者_JAVA技巧
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;
}
What am I doing wrong?
employeeList
is a list of type ManpowerManager.MainWindow.Employe
therefore you cannot insert a string into it.
I think you may want something like this:
employeeList.Insert(position, new Employee(loginId));
you need to insert a new Employee:
employeeList.Insert(position, new Employee(loginid)
{
FirstName = "steve", // or whatever you want to initalize (or not)
} );
you are attempting to insert a string into a list of Employee objects, thus your errors.
as an aside, you are assigning null (default(List<Employee>)
), and then on the next line, assigning a new List. you can do this in one line: List<Employee> employeeList = new List<Employee>();
精彩评论