المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Problem with adding new record to the datagridview with Master/Child relationship



C# Programming
10-20-2010, 04:00 PM
Hi,

I am using c# and sql for this simple example and I have two related tables: Master, Details. The Primary Key in Master is MasterId and there is a Foreign Key in Details table to establish the relation. The columns of Master are bound to textbox while the Details table are bound to datagridview. MasterBindingSource and DetailBindingSource are generated automatically. My problem with this is that adding a new Master along with its Details, coz it errors with FK constraint violated. Actually, when I add a new Master, the MasterId value @ the textbox is -1, so the value that was recognized by the Details MasterId @ the datagridview is -1 likewise, so when the insertion is updated to the database, MasterId is automatically set by the db engine due to its identity property. However, this MasterId is not known to the dataset. So when the Details table is updated to the database, the error occurs(Sql Exception was unhandled). So I need help for this problem coz I tried everything but nothing happened.

Anyway, here is my simple code as shown:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace MasterDetail
{
public partial class Form1 : Form
{
//DsMasterDetail ds = new DsMasterDetail();
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
this.masterTableAdapter.Fill(this.dsMasterDetail.Master);
this.detailTableAdapter.Fill(this.dsMasterDetail.Detail);
}
void Master_RowChanged(object sender, DataRowChangeEventArgs args)
{

}

private void masterBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
Validate();
masterBindingSource.EndEdit();
masterTableAdapter.Update(this.dsMasterDetail.Master);

dgvDetail.*******();
detailBindingSource.EndEdit();
detailTableAdapter.Update(this.dsMasterDetail.Detail);
}

private void dgvDetail_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
//e.Row.Cells[1].Value = bnPositionItem.Text;
}
}
}

Thanks in advance, your help will be greatly appreciated.