Click here to Skip to main content
14,937,163 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 2 tables, Parent and Child.
There is a one-to-one DataRelationship between the tables.

I have set up a windows form with detail text boxes for all the fields of both tables. (since the relationship is one-to-one I didn't need a gridvie for the child records).

I have everything set up so that I can move through the ParentBindingSource and all the child fields adjust appropriately to display according to context.

The problem is that I want to Add new Parent AND Child records at the same time.

I have an ADDButton which calls "ParentBindingSource.AddNew()"
When I do this, my autoincrement ParentID field shows a value of -1;
The Child fields go blank;

I have a SAVEButton which calls "ParentTableAdapter.Update()"
This works to save the new Parent record.

PROBLEM: I cannot figure out the sequence of events to add a NEW child record at the same time!

What am I missing???

Thanks
Posted
Comments
[no name] 13-Sep-11 3:31am
   
post what have you done before

Below is my code.
My test is very basic.
The user presses the "New" button and I try to create both a Parent and Child record.
I enter the data on the Form.
I click the "Save" button and try to save the data.

I recognize the need to get the new KeyID to save to the child, but the problem is that when I try to get the child row back that I added, nothing is there...

I believe I must be missing something when I click the New button... When I add the record to the ChildBindingSource perhaps it doesn't get linked to the parent record? Is there a programmatic way to "AddChildRecord"?


private void New_Click(object sender, EventArgs e)
{
ParentBindingSource.AddNew();
ChildBindingSource.AddNew();
}

private void SaveBTN_click( object sender, EventArgs e)
{
ParentBindingSource.EndEdit();
ChildBindingSource.EndEdit();
foreach (DataSet1.ParentRow cr in dataSet11.ParentTable)
{
if (cr.RowState == DataRowState.Added)
{

/*
The call to GetChildRows doesn't return any values!!! ???
*/
DataRow[] childRows = cr.GetChildRows(dataSet11.Relations["Parent_ChildRelation"]);
ParentTableAdapter.Update(cr);
ChildTableRow childRow = (ChildTableRow)childRows[0];
childRow.KeyID = cr.KeyID;
ChildTableAdapter.Update(childRow);

}
}
   
When you INSERT data into a datatable the PrimaryKey Value is not set. This value is needed in the child table as a reference to the parent table. So first add data to parent table. Find the newest PK value and use that value in your insert in your child table.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900