How to refresh DataSource of a ListBox

后端 未结 7 1267
轮回少年
轮回少年 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:20

    I would suggest to use BindingSource as it would properly update connected controls.

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

    Changing controls data source on fly produces strange result sometime.

提交回复
热议问题