Reputation: 199
I have 2 forms (Form1, Form2) each having 1 datagridview with modifier Public and 1 button. The code written on the buttons are:-
Form2 f = new Form2();
f.Show();
f.datagridview1 = datagridview1;
Now when i press the button of Form1, Form2 appears but the values in datagridview1 of Form1 are not displayed in the datagridview1 of Form2 but when i programmatically check for the values in datagridview1 of Form2, the values are there.
Note:- I know i instead of writing f.datagridview1 = datagridview1; i can write a loop to populate the datagridview but i need to know what is the problem with the above code.
Thanks in advance
Upvotes: 0
Views: 60
Reputation: 607
You shouldn't override the reference to the dataGridView (which means that you will access the dataGridView from Form1, even if you access f.dataGridView1 from Form2), but rather set the DataSource from both dataGridViews to the same object.
So the error in your code can be made visible if you add the following line in your code:
Form2 f = new Form2();
f.Show();
f.datagridview1 = datagridview1;
f.datagridview1.DataSource = null;
You will see that, all of a sudden, your datagridview in Form1 will be empty, because datagridview1
AND f.datagridview1
will point to the same datagridview in Form1. Also you can no longer access the datagridview from From2 (at least not that easy).
So maybe try this instead:
f.datagridview1.DataSource = datagridview1.DataSource
This code will just set both DataSources (which contain the actual data) to the same object in both datagridviews.
I hope this explanation is somewhat understandable : )
Upvotes: 1
Reputation: 1318
You could use ResetBindings on the BindingSource object. Like that:
//could be simpler assignment, but to give you a view on what is going on
BindingSource source = new BindingSource();
source.DataSource = f.datagridview1.DataSource;
source.ResetBindings(false);
Let me know if that works for you
Upvotes: 0