简体   繁体   中英

C# Correct Way of Binding a List to a ListBox

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?

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.

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;

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