簡體   English   中英

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

[英]Adding an item to a Generic List in WPF form

我有一個名為employeeList的列表,正在用一個數據表填充該表,該表工作正常。 因此,現在我希望能夠在運行時將(可選)項目添加到列表中。 我以為簡單的List.Insert可以工作,但嘗試執行時卻出現錯誤。 我遇到問題的那一行是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;
    }

我究竟做錯了什么?

employeeListManpowerManager.MainWindow.Employe類型的列表,因此您不能在其中插入字符串。

我認為您可能想要這樣的東西:

employeeList.Insert(position, new Employee(loginId));

您需要插入新員工:

employeeList.Insert(position, new Employee(loginid)
                         {
                           FirstName = "steve", // or whatever you want to initalize (or not)
                         } );

您正在嘗試將字符串插入Employee對象的列表中,從而導致您的錯誤。

順便說一句,您要分配null( default(List<Employee>) ),然后在下一行分配一個新的List。 您可以一行完成此操作: List<Employee> employeeList = new List<Employee>();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM