How to prevent selectindexchanged event when binding DataSource?

I have a ComboBox control (WinForm project).

When I bind a DataSource to a ComboBox control, the combobox_selectedindexchanged event is fired.

Any idea how to prevent the selectedindexchanged event when binding a DataSource?

+8
c # combobox
source share
5 answers

Remove the SelectedIndex_Changed event handler, bind your data, and add the handler back. The following is a simple example of how this can be done with the method:

private void LoadYourComboBox() { this.comboBox1.SelectedIndexChanged -= new EventHandler(comboBox1_SelectedIndexChanged); // Set your bindings here . . . this.comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged); } 
+28
source share

I know this is an old post and it has an accepted answer, but I think that we can use the SelectionChangeCommitted event as a solution to avoid triggering events during data binding.

The SelectionChangeCommitted event fires only when users change the selection in the combo box.

there is a similar question on SO, and this answer is provided by @arbiter.

+9
source share

Do not think that you can stop the event, but you cannot process it.

Disconnect the event handler, bind and attach the event handler.

+2
source share

Use SelectionChangeCommitted Event instead of 'SelectedIndexChanged'

SelectionChangeCommitted occurs only when the user changes the selection of the combo box. Do not use SelectedIndexChanged or SelectedValueChanged to commit user changes, as these events are also raised when the selection changes programmatically.

FROM https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectionchangecommitted.aspx

+1
source share

Here is an easy way. You can use the Tag property for combobox. It can be empty or 0 is an integer value when it is empty or not yet executed. You must set the combobox tag as the number of elements after the limit. In the SelectedValueChanged event, if the Tag property is null or 0, you must return from void.

Here are some examples from my project.

 private void cb_SelectedValueChanged(object sender, EventArgs e) { if (!(sender is ComboBox)) return; ComboBox cb = sender as ComboBox; if (DataUtils.ToInt(cb.Tag, 0) == 0) return; if (cbSmk.SelectedValue == null ) return; /* Continue working; */ } public static void ComboboxFill(ComboBox cb, string keyfld, string displayfld, string sql) { try { cb.Tag = 0; cb.DataSource = null; cb.Items.Clear(); DataSet ds = DataMgr.GetDsBySql(sql); if (!DataUtils.HasDtWithRecNoErr(ds)) { cb.Text = "No data"; } else { cb.DataSource = ds.Tables[0]; cb.DisplayMember = displayfld; cb.ValueMember = keyfld; } cb.Tag = cb.Items.Count; } catch (Exception ex) { Int32 len = ex.Message.Length > 200 ? 200 : ex.Message.Length; cb.Text = ex.Message.Substring(0, len); } } CmpHelper.ComboboxFill(cbUser, "USER_ID", "USER_NAME", "SELECT * FROM SP_USER WHERE 1=1 ORDER by 1",-1); 
0
source share

All Articles