Reputation: 1373
I have a UserControl in which I've put a dropdown ComboBox and a DataGridView.
The ComboBox is a Filter containing items depending of the data in my DataGridView. The objects in the DataGridView have a property called ProductType. For every ProductType in the DataGridView, the ComboBox Filter adds it to the filter option.
The DataGridView needs to be refreshed when the following events occur:
The ComboBox is reinitialised when I refresh the data grid, since the list of ProductType present in the Grid might've change.
The problem is that when I click the refresh button, the refresh function gets called multiple times. Clicking the refresh button triggers RefreshButton_Clicked. The refresh reinitialise the ComboBox. Reinitialising the ComboBox triggers ComboBox_SelectedItemChanged since the selected Item is no longer the same. Then I have to put the item that was selected prior to the refresh, so another ComboBox_SelectedItemChanged is triggered. Etc.
Is there a way to suspend an event listener while I refresh and resume it afterwards ?
Upvotes: 0
Views: 187
Reputation: 1001
You can temporaily remove the event by doing a "-=" operation.
For e.g if you registered an event like this
this.ComboBox1.SelectedIndexChanged +=
new System.EventHandler(ComboBox1_SelectedIndexChanged);
you can temporarily unregister by
this.ComboBox1.SelectedIndexChanged -= ComboBox1_SelectedIndexChanged;
When you make the service/db call for updating/filtering the options. You can unregister the event and register them back after your data is fetched. I usually like to have the async event pattern for fetching backend data and I unregister my events(or in cases disable my UI buttons,forms etc) when I make the service call and enable/register them in the on completed call back.
Upvotes: 2
Reputation: 10444
You could use a bool _isRefreshing;
to indicate that you're currently in process.
The refresh button "hiding" its action seems like a code smell, to me. It's preferable for the subscriber to decide when it should or should not carry out its method.
if (!_isRefreshing)
The reality is that the event is happening, so disabling the listener obscures reality... What if there is some other listener which doesn't cause this update loop? You'd be affecting it as well.
So you want both worlds: the event fires properly and listeners decide they shouldn't act.
Upvotes: 2