简体   繁体   English

C#中DataGridView的SQL数据更新问题

[英]Data update problem in SQL from DataGridView in C#

I have two tables in SQL server and I have a form purchaseinvoiceform .我在 SQL 服务器中有两个表,我有一个表格purchaseinvoiceform it uses a DataGridView to save multiple products.它使用DataGridView来保存多个产品。

In save mode this works well.在保存模式下,这很有效。 But when I update any order it's updating only the first table which is purchaseinvoice , but isn't updating the second table purchaseinvoicedetails .但是当我更新任何订单时,它只更新第一个表purchaseinvoice ,而不更新第二个表purchaseinvoicedetails purchaseinvoicedetails saves multiple products by their ordernumber . purchaseinvoicedetailsordernumber保存多个产品。 If I have one item in datagridview it saves successfully.如果我在datagridview有一项,它会成功保存。 Now when I update this one item, no problem occurs.现在当我更新这一项时,没有问题发生。 But when I add one more item in this order and try to update it, it does not save the other items.但是当我按此顺序再添加一个项目并尝试更新它时,它不会保存其他项目。

Update query:更新查询:

SaveOrUpdateProductDetailsOnly("UPDATE [dbo].[PurchaseInvoiceDetails] SET [ProductCode] = @ProductCode ,[ProductName] = @ProductName ,[Box] = @Box,[Quantity] = @Quantity ,[Price] = @Price,[DiscountInPercent] = @DiscountInPercent ,[DiscountAmount] = @DiscountAmount,[Amount] = @Amount WHERE PurchaseInvoiceNo = @PurchaseInvoiceNo");

Here is the Code这是代码

How about this?这个怎么样?

private void btnUpdate_Click(object sender, EventArgs e)
{

    using (SqlConnection con = new SqlConnection("Server=your_server_name;Database=your_database_name;Trusted_Connection=True;"))
    {

        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Courses", con))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                {
                    SqlCommandBuilder sqlcmd = new SqlCommandBuilder(da);
                    DataSet ds = new System.Data.DataSet(); // remove this line
                    da.Update(this.ds, "Courses");
                }
            }
        }
    }
}

我认为如果您想更新第二个表中的所有记录,您需要将所有 cmd.parameters 放在 foreach 语句中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM