简体   繁体   中英

Update Listbox when using ObservableCollection

I have an ObservableCollection bound to a listbox like this:

string[] selection = comboEmail.GetItemText(comboEmail.SelectedItem).Split(',');

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

It adds the data to the listbox(listEmail), however, how do I update it after removal. This is what I've tried so far:

int indexRemoval = listEmail.SelectedIndex;
displayEmp.RemoveAt(indexRemoval);
listEmail.DataSource = displayEmp;
//listEmail.Refresh();

but it doesn't work. How would I update the list after a user as clicked the remove button?

You need to set the ItemSource instead of the DataSource. This assumes that you have also set the DataContext .

listEmail.ItemSource = displayEmp;

Since you have defined your displayEmp as ObservableCollection , your updates should reflect automatically.

EDIT: Here is a sample for your reference using BindingList which auto refreshes the UI:

public BindingList<Data> DataList { get; set; }

public void Load()
{
    DataList = new BindingList<Data>
                   {
                        new Data
                            {
                                Key = "Key1",
                                Value = "Value1"
                            },
                        new Data
                            {
                                Key = "Key2",
                                Value = "Value2"
                            },
                        new Data
                            {
                                Key = "Key3",
                                Value = "Value3"
                            }
                    };
     listBox1.DataSource = DataList;
     listBox1.DisplayMember = "Value";
     listBox1.ValueMember = "Key";
}

public class Data
{
     public string Key { get; set; }
     public string Value { get; set; }
}   

private void button1_Click(object sender, EventArgs e)
{
    DataList.RemoveAt(1);
}

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