Click here to Skip to main content
15,892,643 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Guys
In my windows application project I am using Dataset. There are three tables:

Product
---------------
Title, ID, Price

Invoice
---------------
ID, Date, Description

InvoiceItem
---------------
ID, Product_ID, Invoice_ID, Quantity

All ID columnns are Identity and tablename_ID format columns are foreign Keys.

In a single form named BuyForm I get all inputs and then in a Save_ButtonCLick I want to Insert these information to the related tables I have mentioned.
After some googling I found this article:
Inserting relational data using DataSet and DataAdapter
Here is my code according to what I understand from that article:
C#
DataRow invoice = DataSet.Tables["Invoice"].NewRow();
        invoice["Date"] = DateConverter.ToPersianDate();
        invoice["Description"] = string.Empty;
        DataSet.Tables["Invoice"].Rows.Add(invoice);
                    
        DataRow product = null;
        DataRow invoiceItem = null;
        foreach (DataGridViewRow row in ProductGridView.Rows)
        {
            product = DataSet.Tables["Product"].NewRow();
            invoiceItem = DataSet.Tables["InvoiceItem"].NewRow();
        
            product["Title"] = row.Cells["ProductColumn"].Value.ToString();
            product["BuyPrice"] = row.Cells["BuyPriceColumn"].Value;
            product["SellPrice"] = row.Cells["SellPriceColumn"].Value;
            invoiceItem["Count"] = row.Cells["CountColumn"].Value;
        
            invoiceItem.SetParentRow(invoice);
            product.SetParentRow(invoice);
            DataSet.Tables["Product"].Rows.Add(product);
            DataSet.Tables["InvoicItem"].Rows.Add(invoiceItem);
        
            TableAdapterManager.UpdateAll(DataSet);              
         }

This error occurs at time of adding invoiceItem to its DataTable:
Column 'Product_ID' does not allow nulls.

How should I change my code?
Thanks
Posted
Updated 30-Jul-15 10:11am
v3
Comments
[no name] 30-Jul-15 16:31pm    
Either set a value for Product_ID or change the database to allow null values for that column.
Meysam Toluie 30-Jul-15 21:08pm    
the ID columns is Identity and I am using disconnected architecture. did you see?

1 solution

You don't specify the Product_Id for an InvoiceItem and that causes the problem. The Identity fields are used only for primary keys and based on you description, Product_ID is a foreign key so you must define the value for it, one way or another. So probably you should have
C#
invoiceItem.SetParentRow(product);

As a side-note the row
C#
product.SetParentRow(invoice);

looks odd since I doubt that invoice is a parent of product.
 
Share this answer
 

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