Consider the common situation where a parent form displays a list of records in a DataGridView, and a child form displays that same list of records in single-form view. The user opens the child form by double-clicking on a row in the DGV, or by clicking a button in a toolbar. The user can navigate through the list of records in both the parent and child form, and in fact, as the user moves through the records in the child form, the selection bar in the parent's form DGV moves up and down in synch.
This is done by sharing the BindingSource, which is done by passing the BindingSource from the parent to the child form.
private void toolEdit_Click(object sender, EventArgs e)
{
var form = new RequestsForm(requestsObj);
form.Show();
}And what is requestsObj? It's an instance of
public class DBRequests
{
public DSRequests dsRequests = new DSRequests();
public RequestsTableAdapter requestsTableAdapter = new RequestsTableAdapter();
public BindingSource requestsBindingSource = new BindingSource();
public DBRequests()
{
requestsBindingSource.DataSource = dsRequests;
requestsBindingSource.DataMember = "Requests";
requestsBindingSource.AddingNew += RequestsBindingSource_AddingNew;
}
private void RequestsBindingSource_AddingNew(object sender, AddingNewEventArgs e)
{
var bs = sender as BindingSource;
var dv = bs.List as DataView;
var drv = dv.AddNew() as DataRowView;
drv.Row.SetField<DateTime>("Entered", DateTime.Now);
e.NewObject = drv;
}
}Over in the child form, we have (some code snipped for brevity)
private void toolOk_Click(object sender, EventArgs e)
{
if (ValidateChildren())
{
incomingObject.requestsBindingSource.EndEdit();
incomingObject.requestsTableAdapter.Update(incomingObject.dsRequests.Requests);
formMode = FormMode.View;
DisplayCurrent();
}
}And it works great. Any changes made in the child form are reflected immediately in the DataGridView of the parent form.
Oh, but we can never be happy, can we? Now the problem is this: you can't open two records, each in their own child form, for example, to compare them side by side. This is because the BindingSource has only one Position property, and if you change it, it reflects in every control that is bound to it.
You can open multiple child forms, each with their own BindingSource, but then changes made are not automatically reflected in the parent form's DGVbecause it's not the same BindingSource.
So... if I share the BindingSource, changes are reflected across forms, but the BindingSource can only be on one record at a time. On the other hand, if I give each their own BindingSource, changes don't ripple across them.
Is there a ring that binds them all?
If there isn't, what is the most efficient way of refreshing the contents of a DataGridView?
Or let me put it this way, how would you display a parent form and then allow multiple child forms to open, with any changes made in those child forms reflecting in the parent form?