Stop comboBox's selectedIndexChanged event from firing when the form loads - winforms

I have a form with a ComboBox that provides a dropdownlist. On the comboBox's SelectedIndexChanged event, am running some code, but I don't want that code to run when the form loads. Unfortunately, when I load the form (before I make a selection in the combobox), SelectedIndexChanged of the combobox fires (I think when the combobox is databinding). Is there a way of avoiding such behaviour?

If you want to react only when the user change the selected item in the combo box, then it is better to subscribe to SelectionChangeCommitted.

You can simply unbind the SelectedIndexChanged event, call your fill function and bind the SelectedIndexChanged event again. Unfortunately, this doesn't work with a grid.
For example:
this.cmb.SelectionChanged -= new System.EventHandler(this.cmb_SelectionChanged);
cmb.fill(); //Your function
this.cmb.SelectionChanged += new System.EventHandler(this.cmb_SelectionChanged);

Be sure to set the DataSource property in your onload() function after assigning the ValueMember and Datamember properties.
This will help you to solve your problem!

Why not have a boolean flag that indicates when your Form has finished loading?
In your SelectionChanged event, check if the boolean flag is true. If it is true then handle the event, otherwise ignore it.

VB
RemoveHandler lbxNomes.SelectedIndexChanged, AddressOf lbxNomes_SelectedIndexChanged
lbxNomes.DataSource = dst
Label1.Text = String.Format("Encontrados {0} Sócios nesta pesquisa", dst.Rows.Count)
Label1.Visible = True
AddHandler lbxNomes.SelectedIndexChanged, AddressOf lbxNomes_SelectedIndexChanged

Here is a simple solution that leaves your code almost untouched:
In the SelectedIndexChanged event, check if the myComboBox handle is created using the (IsHandleCreated) method. Another added check is to check if the user is actually focusing your combobox control to change selected index.
private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (myComboBox.IsHandleCreated && myComboBox.Focused)
{
// Do something here
}
}

It worked for me in a way with the following code:
private void ddlChapter_SelectionChangeCommitted(object sender, EventArgs e)
{
if (ddlChapter.SelectedValue != null)
{
// Do something here
}
}

Related

WPF Datagrid OnPropertyChanged causes SelectionChanged event

I have a WPF Datagrid that is bound to a model.
Inside the model I have a property defined as
public String status
{
get
{
return m_status;
}
set
{
m_status = value;
OnPropertyChanged("status");
}
}
This property informs the grid of changes via OnPropertyChanged.
I also handle the SelectionChanged event to trigger different activities.
SelectionChanged="gridSongs_SelectionChanged"
private void gridSongs_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Console.WriteLine("gridSongs_SelectionChanged " + sender.ToString());
}
During testing this I have noticed that every time I change the property "status" in code the grid updates automatically (which is what I want) but also fires the SelectionChanged Event as well.
Is there any way I can stop the event from firing when I change the model from code but let it go through when user clicks an item in the grid ?
Maybe I could use a different event for the manual selection of items in the grid ?
thanks a lot in advance.
Is there any way I can stop the event from firing when I change the model from code but let it go through when user clicks an item in the grid?
No, but there is a simple workaround. Add a private bool isLocal variable and set it to true before you make any changes and back to false afterwards:
isLocal = true;
status = "Some Value";
isLocal = false;
Then, in your SelectionChanged handler, check this variable and only react if it is false:
private void gridSongs_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!isLocal ) Console.WriteLine("gridSongs_SelectionChanged " + sender.ToString());
}

Silverlight SDK DataGrid not always fire MouseLeftButtonUp event?

Why does the DataGrid not always fire the MouseLeftButtonUp event?
I try to implement a single click behaviour on DataGridTextColumn and bind to this event.
dataGrid.MouseLeftButtonUp += OnDataGridMouseLeftButtonUp;
In the handler I call BeginEdit() and set focus on the TextBox element. It works when I get the event, but it is not always fired? Does anyone know how to fix that?
Thanks!
Try using AddHandler instead.
dataGrid.AddHandler(UIElement.MouseLeftButtonUpEvent,
new MouseButtonEventHandler(OnMouseLeftButtonUp), true)
...
private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
// etc...
}

How to know when binding is completed?

When I set the .ItemSource() property on a DataGrid to a Collection, the call returns fast, but the actual binding happens afterwards. Since I want to display a waiting cursor, I need to detect when the actual binding has finished. Is there any event for this?
Anything based on ItemsControl uses an ItemContainerGenerator to generate its items in the background. You can access the ItemContainerGenerator property of the DataGrid and hook up the StatusChanged event to determine when it's done. If you're using virtualization and scroll, this will fire again so you need to handle that if necessary in your case.
I waited for my DataGrid's Loaded event to fire, and I did a BeginInvoke, like this:
private void SubjectsList_Loaded(object sender, RoutedEventArgs e)
{
Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() => ColorMyRows()));
}
More details available in my answer here: https://stackoverflow.com/a/44464630/2101117
Your best bet is to hook into OnPropertyChanged event in your Window or User Control. This event is fired every time a property is updated. Then check for the actual property you wish to observe and take action.
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
if ("YOUR_PROPERTY_NAME".Equals(e.Property.ToString()))
{
// Take action
}
base.OnPropertyChanged(e);
}

WPF TextBox lostfocus as attached property

I have a Grid with many TextBoxes and I want to call NotifyPropertyChanged() method to update some other controls everytime one of these TextBox-es changed the value = lost the focus (I don't want to use PropertyChanged as UpdateSourceTrigger)
This is what I can do:
<Grid TextBoxBase.TextChanged="My_TextChanged" >
...
</Grid>
I need something like:
TextBoxBase.OnLostFocus
Use the lost focus event
TextBox.LostFocus="OnTextBoxLostFocus"
Filter on textboxes ;)
private void OnTextBoxLostFocus(object sender, RoutedEventArgs e)
{
if(!(e.OriginalSource is TextBox))
return;
//Do stuff
}
If your properties are not changed, your Textboxes will not be updated however. You should consider mutating the data those other TextBoxes are bound to, instead of using LostFocus to update your model.
Good luck!
TextBoxBase.LostFocus is, I suspect, the event you're looking for.
It's listed here: http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.textboxbase_events.aspx - but it's defined on UIElement - so you possibly want to try UIElement.LostFocus if the above doesn't work in markup.

Canceling SelectedIndexChanged in WinForm ListView

The winform ListView doesn't seem to have an easy way to cancel the SelectedIndexChanged event. I don't see a SelectedIndexChanging event either.
The code is my attempt. However the hightlight is gone and I was wondering if I need to color the selection also or if there's a better way to cancel. _prevSelectedIndex is the index from the last selection. I want the highlight to go back to the previous selection.
lvSearchResults.SelectedIndexChanged -= new EventHandler(lvSearchResults_SelectedIndexChanged);
lvSearchResults.SelectedIndices.Clear();
lvSearchResults.SelectedIndices.Add(_prevSelectedIndex);
lvSearchResults.Items[_prevSelectedIndex].Selected = true;
lvSearchResults.SelectedIndexChanged += new EventHandler(lvSearchResults_SelectedIndexChanged);
The best and easy way is to have a boolean property which you set to say, true when you dont want the event to fire. In the SelectedIndexChange event, you test to see if you should allow the event to continue firing else you return. Check my code out. The code below behaves the same.
//somewhere on top
private bool dontFireEvent = false;
//somewhere else
dontFireEvent = true;
treeView1.SelectedNode = treeView1.Nod.... bla bla //event won't fire
dontFireEvent = false;
//within the event code
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (!dontFireEvent)
ProcessLogin();
}
As long as you have multiselect turned off you shouldn't have to call
SelectedIndices.Clear() Selectedndices.Add(..)
as well as:
Items[_prevSelectedIndex].Selected = true;
The latter will accomplish the same result.
I believe you're also adding a continually growing list of event handlers. To remove an event handler you have to store an instance of the delegate then remove that instance;-= new EventHandler(...) isn't going to remove the handler.

Resources