You don't have to do any of that. Pretty much all you have to do is add the data and, when you're done, save it. Everything else happens automatically.
The first step is to make sure the grids are bound correctly. Here's how to perform parent/child data-binding:
Master/Detail (Parent/Child) Data-binding (.NET 2.0+ WinForms)
Once that's done you are good to go. You add a parent record to the parent grid and the DataTable automatically generates a temporary ID that may or may not be the same as the permanent ID that will eventually be generated by the database. It doesn't matter either way. The child grid will display all the child records related to the currently selected parent. That parent is new so the child grid is empty. You then add a new record to the child grid. The one manual step you do need to perform is get the ID from the current parent, which you can get from the Current property of the parent BindingSource, and assign that to the foreign key field of the new child. The DataTable will also generate a temporary ID for the child record. You can keep doing that as much as you want, adding as many parents as you want and as many children to each parent as you want.
Now, when it comes time to save, you must save the parent DataTable first. All the new parent records will get inserted into the database and permanent IDs will get generated for them. If you've configured you're adapter correctly, those IDs will get propagated back to the parent DataTable. Because you have configured your DataRelation to cascade updates, those new IDs will also get propagated to the child DataTable. You can then save the child records and they will be inserted with the correct foreign key values.
One point to note is that, if you're deleting records, you must delete children before deleting parents but you must insert parents before inserting children. As a result, you may have to do your entire save in four stages instead of two.
Bookmarks