Chrez
Chrez

Reputation: 133

List<T>.Add Doesn't add to the list

Well the problem is that my count on the list is not rising so it's not adding the object to the list.

List<Employee> employees = new List<Employee>();

private void addEmployee_Click(object sender, EventArgs e)
{
    List<Employee> employees = new List<Employee>();

    employees.Add(new Employee()
    {
        egn = egnInput.Text,
        names = namesInput.Text,
        proffesion = professionList.Text,
        office = officeList.Text,
        salary = Double.Parse(salaryInput.Text),
        joinDate = DateTime.Parse(joinDatePicker.Text)
    });

    MessageBox.Show("Служителя бе добавен успешно!");

    egnInput.Clear();
    namesInput.Clear();
    professionList.Text = "";
    officeList.Text = "";
    salaryInput.Clear();
    joinDatePicker.Text = "";

}

Thanks in advance!

Upvotes: 0

Views: 122

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56413

Don't define the list inside addEmployee_Click, rather make it global like below:

List<Employee> employees = new List<Employee>(); // make this global to the class

private void addEmployee_Click(object sender, EventArgs e)
{
    employees.Add(new Employee()
    {
        egn = egnInput.Text,
        names = namesInput.Text,
        proffesion = professionList.Text,
        office = officeList.Text,
        salary = Double.Parse(salaryInput.Text),
        joinDate = DateTime.Parse(joinDatePicker.Text)
    });

    MessageBox.Show("Служителя бе добавен успешно!");

    egnInput.Clear();
    namesInput.Clear();
    professionList.Text = "";
    officeList.Text = "";
    salaryInput.Clear();
    joinDatePicker.Text = "";
}

Upvotes: 0

Salah Akbari
Salah Akbari

Reputation: 39946

Because you have defined the List in addEmployee_Click event and so every time you click the Button the List is created again. You should remove the following line in your addEmployee_Click event because you have already declared it globally:

List<Employee> employees = new List<Employee>();

Upvotes: 7

Related Questions