Folks, this is just another heads up and reminder to myself about a gotcha.
BindingSource mybinder;
DataGridView mygrid;
mygrid.DataSource = mybinder;
mygrid.SelectionChanged += ...
mybinder.DataSource = ...
I have noticed over the years that the WinForms DataGridView control raises
multiple SelectionChanged events (usually 3) just after the DataSource is
set. Thereafter your get one event as expected when the selection changes.
Occasionally I will put a bit of guard code around the initial burst of
events to improve performance if necessary, but doing this always irritated
me as a hack.
It turns out the best thing to do is not listen to the grid at all, listen
to the binding source like this:
mybinder.PositionChanged += mybinder_PositionChanged ...
mybinder.DataSource = ...
:
private void mybinder_PositionChanged(object sender, EventArgs e)
{
if (mybinder.Position >= 0)
{
// cast mybinder.Current to a DataRowView or similar entity in the
data source
}
}
This behaves correctly and raises a single event when the selection changes
in all cases.
However, I'm not sure how to avoid the quirk when you don't use a
BindingSource and just bind the grid's DataSource directly.
Greg