简体   繁体   中英

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>();

        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>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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