简体   繁体   English

以WPF形式向通用列表添加项目

[英]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. 我有一个名为employeeList的列表,正在用一个数据表填充该表,该表工作正常。 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. 我以为简单的List.Insert可以工作,但尝试执行时却出现错误。 The line I having issues with is the employeeList.Insert and the two errors are included in the code block. 我遇到问题的那一行是employeeList.Insert,这两个错误包含在代码块中。

    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;
    }

What am I doing wrong? 我究竟做错了什么?

employeeList is a list of type ManpowerManager.MainWindow.Employe therefore you cannot insert a string into it. employeeListManpowerManager.MainWindow.Employe类型的列表,因此您不能在其中插入字符串。

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. 您正在尝试将字符串插入Employee对象的列表中,从而导致您的错误。

as an aside, you are assigning null ( default(List<Employee>) ), and then on the next line, assigning a new List. 顺便说一句,您要分配null( default(List<Employee>) ),然后在下一行分配一个新的List。 you can do this in one line: List<Employee> employeeList = new List<Employee>(); 您可以一行完成此操作: List<Employee> employeeList = new List<Employee>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM