4

I have a ComboBox with a DataSource set to application settings as follows

public DetailsForm()
{
    InitializeComponent();
    this.comboBox1.DataSource = TextSelectionSettings.Default.categories;
}

But I want users to add extra items to the combo box if they need to at runtime. So I just made a simple click event on a textbox to test adding a new string to the list.

private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
    TextSelectionSettings.Default.categories.Add("test");
    TextSelectionSettings.Default.Save();
}

However the ComboBox doesn't show the new string I added to the settings.

How can I refresh the ComboBox to show the changes in the settings?

  • Refresh() function on the combo box did not work.
  • setting the DataSource again did not work either.
  • I cannot add the Item directly to ComboBox using Items.Add() method because the DataSource is set.
erotavlas
  • 4,274
  • 4
  • 45
  • 104

1 Answers1

5

In order for the Data Bindings in Windows Forms (and WPF) to work, it has to have some kind of change-notification like IBindingList or INotifyCollectionChanged to be able to notice the changes.

  • Calling Refresh() is simply for painting and doesn't refresh the bindings
  • Setting the .DataSource to the same thing won't work (you don't change anything, so it doesn't notice it as a change)

The work-around is to set the .DataSource to null and then set it back to the collection again. This causes it to re-evaluate the binding (because it is a different object than the current null one) and reset your values.

Ron Beyer
  • 11,003
  • 1
  • 19
  • 37
  • `INotifyPropertyChanged` is completely irrelevant to the problem. Relevant interface for this problem (receiving `ListChanged` notifications) is `IBindingLust` as described in the [linked post](https://stackoverflow.com/a/33625054/3110834). – Reza Aghaei Apr 05 '18 at 21:22
  • @RezaAghaei I removed it, although for other Data bindings `INotifyPropertyChanged` would be relevant to data binding (things like Textbox), but yes, not relevant in this scenario. – Ron Beyer Apr 05 '18 at 21:24