Home > Net >  How to add objects to a list
How to add objects to a list

Time:08-18

How can I add objects to a list? I have a list view and every time I create a new employee it seems like I am overwriting the previous one. What could be the most programmatically way of create and adding to the listview a new object? Thank you.
My code:

        private void btnCreateNewEmployee_Click(object sender, RoutedEventArgs e)
    {
        //Get values from cboBox anda datetimepickers (local variables)
        double salaryEmp = double.Parse(txtSalary.Text);
        int cellphone = int.Parse(txtCellphone.Text);
        DateTime hiring = dtHiring.Date.DateTime;
        DateTime birth = dtBirth.Date.DateTime;

        //List of new members object of class Employees
        List<Employees> employees = new List<Employees>();

        //Call the class and add a new member to the list Employee
        employees.Add(new Employees(txtName.Text, txtLastName.Text, txtEmail.Text, txtAddress.Text, cboEmployeeType.Text, cboDepartment.Text, salaryEmp, cellphone, hiring, birth));

        //Populate listview with member objects
        lvwEmp.ItemsSource = employees;
    }

Here are images of the result
[employee1]: https://i.stack.imgur.com/bBn1V.png
[employee2]: https://i.stack.imgur.com/udXQo.png

CodePudding user response:

Just declare your employees List object outside of the function and it will just works fine,I hope it will help.

CodePudding user response:

The issue with your code is that you are creating a new list and adding a new object to your list every time you click a button.

Use an ObservableCollection<Employee> instead of List<Employee> since you are using a UWP. This helps to notify the UI everytime you update the list by adding, deleting or editing.

Do something like this:

    //Declare your list outside the button click.
     ObservableCollection<Employee> employees = new ObservableCollection<Employee>();

    private void btnCreateNewEmployee_Click(object sender, RoutedEventArgs e)
    {
        //Call the class and add a new member to the list Employee
        employees.Add(new Employees(txtName.Text, txtLastName.Text));

        //Populate listview with member objects
        lvwEmp.ItemsSource = employees;
    }

Please read more on Microsoft docs

  • Related