C# Correct Way of Binding a List to a ListBox

69 Views Asked by At

Assume I have the following code:

        private List<Employee> displayEmp;

        public Form1()
        {
            InitializeComponent();
            displayEmp = new List<Employee>();
        }

In my Add Button handler:

   private void button1_Click(object sender, EventArgs e)
        {
            string[] selection = comboEmail.GetItemText(comboEmail.SelectedItem).Split(',');

            Employee add = new Employee(Convert.ToInt32(selection[0]), selection[1], selection[2], selection[3]);

            if (!(comboEmail.SelectedIndex == 0))
            {

                if(!(listEmail.Items.Contains(add))){

                      displayEmp.Add(add);;
                      listEmail.DataSource = null;
                      listEmail.DataSource = displayEmp;
                }
                else
                {
                    MessageBox.Show(add.ToString() + " Already Added.");
                }

            }

        }

My Remove Button Handler:

private void button2_Click(object sender, EventArgs e)
{

    int indexRemoval = listEmail.SelectedIndex;

    if (indexRemoval != -1)
    {
        displayEmp.RemoveAt(indexRemoval);
        listEmail.DataSource = null;
        listEmail.DataSource = displayEmp;
    }

}

I have a list of employees in a ComboBox that when selected, I add to a listbox. In the my add/remove button handlers, am I doing it correctly? What is the proper practice when you have a collection binded to a control, and you want to add/remove items?

2

There are 2 best solutions below

0
On

Yes, you are binding your collection correctly.

I would also do:

listEmail.DisplayMember = "Name";

Name being whatever property within 'Employee' you want displayed in the listbox, else it will try to convert the object to a string.

0
On

Common practice is to use ObservableCollection<T> instead of List<T>.

    private ObservableCollection<Employee> displayEmp;

    public Form1()
    {
        InitializeComponent();
        displayEmp = new ObservableCollection<Employee>();
        // you need to assign DataSource only once
        listEmail.DataSource = displayEmp;
    }

ObservableCollection implements INotifyCollectionChanged interface, that informs ListView about all changes in collection (adding and removing intems). As ObservableCollection informs about changes, you don't need to forcefully refresh bindings so there is no need for

    listEmail.DataSource = null;
    listEmail.DataSource = displayEmp;