erotavlas
erotavlas

Reputation: 4493

Modifying original DataSource doesn't update ComboBox

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?

Upvotes: 5

Views: 4522

Answers (1)

Ron Beyer
Ron Beyer

Reputation: 11273

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.

Upvotes: 6

Related Questions