Reputation: 447
I've got a simple winform with a bindingSource using a List as Data. I'd like to take action whenever the binding sources position is changed. Reading up, it looks like the 'positionChanged' event is what I need. However, in my app I'm unable to get this event to fire.
There is a bindingNavigator to use the bindingSoure for navigation and (for debugging) a button that changes the current binding source position.
I've tried to simplify this as much as possible. My form code looks like this :
public partial class Form1 : Form
{
protected List<int> data;
public Form1()
{
InitializeComponent();
data = new List<int>();
data.Add(4);
data.Add(23);
data.Add(85);
data.Add(32);
}
private void Form1_Load(object sender, EventArgs e)
{
bindingSource1 = new BindingSource();
bindingSource1.DataSource = data;
bindingNavigator1.BindingSource = this.bindingSource1;
}
private void bindingSource1_PositionChanged(object sender, EventArgs e)
{
// Debugger breakpoint here.
// Expectation is this code will be executed either when
// button is clicked, or navigator is used to change positions.
int x = 0;
}
private void button1_Click(object sender, EventArgs e)
{
bindingSource1.Position = 2;
}
}
The eventHandler is autogenerated in the designer :
//
// bindingSource1
//
this.bindingSource1.PositionChanged += new System.EventHandler(this.bindingSource1_PositionChanged);
Now, the trouble is that whenever I run this, the 'PositionChanged' event just will not trigger. I've verified that bindingSource1.Position changes based on the navigator and the button. But no matter what I do, the event won't actually trip. I'm guessing this is something pretty stupid at this point, or I'm completely misinterpreting when the event is supposed to fire.
Using .NET 4.5
Upvotes: 2
Views: 6969
Reputation: 11277
The problem is in your Form_Load
private void Form1_Load(object sender, EventArgs e)
{
// this overrides the reference you have created in the desinger.cs file
// either remove this line
bindingSource1 = new BindingSource();
// or add this line
// bindingSource1.PositionChanged += bindingSource1_PositionChanged;
bindingSource1.DataSource = data;
bindingNavigator1.BindingSource = this.bindingSource1;
}
When you create the the new object new BindingSource()
, it doesn't have the event PositionChanged
subscribed. That is why you never hit your breakpoint.
Upvotes: 4