BindingSource xxxChanged Event Behavior

8 มี.ค.

Some observations on .NET BindingSource CurrentChanged/PositionChanged/ListChanged event behaviors. Here’s the code for producing the observations.

private DataTable table = new DataTable();
private int i = 1;

private void Form1_Load(object sender, EventArgs e)
{
    // Hack: To prevent CurrentChanged from raising more than once, uncomment the line below.
    // bindingSource1.DataSource = table;

    table.Columns.Add("c1", typeof(string));
    for (int j = 0; j < 5; j++)
    {
        var row = table.NewRow();
        row["c1"] = "row " + i;
        i++;
        table.Rows.Add(row);
    }
    dataGridView1.DataSource = bindingSource1;
    bindingSource1.DataSource = table;
}

When we set DataSource for bindingSource1, CurrentChanged event is raised 3 times, ListChanged event twice, and PositionChanged event once.

When removing the last row, PositionChanged is raised twice (Position set to -1), while CurrentChanged and ListChanged are raised once per each event.

Clearing the table has the same effect has removing the last row.

Removing the first row (when there are more rows below) does not raise PositionChanged event because the Position stays the same. Only the selected value changes.

In summary:

  • CurrentChanged works well in general, but we need to apply some hack to make sure the event is not raised many times on first initialization.
  • PositionChanged works well for initialization, but not for tracking addition, removal, or clearing. Use it if you only care about position, and be aware that clearing raises the event twice.
  • ListChanged…haven’t found a use case for it yet.

Update (Mar 8, 2010)…
After playing with the code some more, a semi-automatic approach will hopefully keep me more sane while debugging in the long run. The idea is when setting the DataSource, use unsubscribe-resubscribe procedure as mentioned in this post, then get the Current value manually. When adding, removing, clearing, selecting items, use CurrentChanged event as usual.

ใส่ความเห็น

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / เปลี่ยนแปลง )

Twitter picture

You are commenting using your Twitter account. Log Out / เปลี่ยนแปลง )

Facebook photo

You are commenting using your Facebook account. Log Out / เปลี่ยนแปลง )

Connecting to %s

Follow

Get every new post delivered to your Inbox.