Ruben
Ruben

Reputation: 2558

Two BindingSource objects with same DataSource property

I have some difficulties with understanding BindingSource's behaviour. Let's look at following example:

  1. Creating table

    DataTable dt = new DataTable();

    dt.Columns.Add("id", typeof(int));

    dt.Rows.Add(new object[] { 0 });

    dt.Rows.Add(new object[] { 1 });

    dt.Rows.Add(new object[] { 2 });

    dt.Rows.Add(new object[] { 3 });

  2. Creating two BindingSource objects with same DataSource property

    BindingSource bs1 = new BindingSource();

    BindingSource bs2 = new BindingSource();

    bs1.DataSource = dt;

    bs2.DataSource = dt;

At this point I supposed, that created BindingSource are fully independent. But really it is not so. After changing Filter property of bs1:

`bs1.Filter = "id >= 2";`

Filter property of bs2 doesn't change, but RowFilter property of underlying DataView (List property of BindingSource) of both BindingSource objects is changed.

It turns out that both BindingSource objects have exactly same instance of DataView i.e. condition bs1.List == bs2.List is true.

My question is why they share same List and how one can change this behaviour?

EDIT: I've found explanation for "why they're sharing same List?" - it seems that List is assigned from DataTable's DefaultView property (so both bs1.List == bs2.List, bs1.List == dt.DefaultView are true).

Upvotes: 2

Views: 3407

Answers (3)

Yash
Yash

Reputation: 314

Ruben's answer didn't work for me but pointed me in right direction. I had to set filter in binding source to make it work. Below is the code that worked for me

BindingSource bs1 = new BindingSource();
BindingSource bs2 = new BindingSource();
bs2.Filter = "My Filter"; // Instead of setting filter on DataView, I had to set it on binding source.
bs1.DataSource = new DataView(dt);
bs2.DataSource = new DataView(dt);
//bs2.DataSource = new DataView(dt, RowFilter: "My Filter", Sort: "", RowState: DataViewRowState.CurrentRows); // This does not work.

Upvotes: 0

Ruben
Ruben

Reputation: 2558

It seems that to change this behaviour one can create two different DataView instances for DataTable and assign them to DataSource property of two BindingSource objects accordingly:

BindingSource bs1 = new BindingSource();
BindingSource bs2 = new BindingSource();
bs1.DataSource = new DataView(dt);
bs2.DataSource = new DataView(dt);

Upvotes: 7

impyre
impyre

Reputation: 87

I'm not yet an expert in C#, but from what I've read I understand this:

by using DataTable dt = new DataTable(); you create only one instance of that object. If that instance changes, it will change for anything that references it.

you'd need to create two instances, and set each instance of BindingSource to reference its own instance of DataTable like so:

DataTable dt1 = new DataTable();

DataTable dt2 = new DataTable();

bs1.DataSource = dt1;

bs2.DataSource = dt2;

Upvotes: 0

Related Questions