How to refresh DataSource of a ListBox

后端 未结 7 1275
轮回少年
轮回少年 2020-11-27 04:39

Form has one Combobox and one ListBox. When the \"Add\" button is clicked, I want to add the selected item from the ComboBox to the ListBox.

public partial c         


        
7条回答
  •  天命终不由人
    2020-11-27 05:12

    Alternatively and probably the most correct way to implement this is to use the provided ObservableCollection. It is designed with the sole purpose of implementing INotifyCollectionChanged.

    public partial class MyForm : Form
    {
        ObservableCollection data = new ObservableCollection();
    
        public MyForm()
        {
            listBox1.DataSource = data;
            listBox1.DisplayMember = "Name";
            listBox1.ValueMember = "Id";
        }
    
        private void buttonAddData_Click(object sender, EventArgs e)
        {
           var selection = (MyData)comboBox1.SelectedItem;
           data.Add(selection);
        }
    }
    

    Because ObservableCollection implements INotifyCollectionChanged the DataSource binding will automatically update the ListBox whenever your data changes.

提交回复
热议问题