如何为两个不同表的文本框和数据网格视图值编写插入查询

本文关键字:数据网 网格 数据 视图 查询 插入 文本 两个 | 更新日期: 2023-09-27 17:58:30

我在winform应用程序中使用文本框和数据网格视图。用户输入的文本框值和数据网格视图值应保存在两个不同的SQL表中,这意味着所有文本框条目保存在一个表中,所有数据网格视图条目保存在另一个表。

我该怎么做?

这是我的存储过程和表PurchasePurchasedetail

CREATE PROC sp_insert_pdtl (
    @purchase_id varchar(15),
    @purchase_date date,
    @ref_no int,
    @product_id int,
    @product_name nvarchar(50),
    @qty int,
    @price float,
    @tax int,
    @discount int,
    @total int
) AS 
begin transaction
INSERT INTO Purchase(purchase_id, purchase_date, ref_no)
VALUES(@purchase_id, @purchase_date, @ref_no)
INSERT INTO Purchasedetail(product_id, product_name, qty, price, tax, discount, total)
VALUES (@product_id, @product_name, @qty, @price, @tax, @discount, @total)
commit`enter code here`

这是我的C#代码。然而,当我执行此操作时,它不会保存这两个表中的数据。

private void SAVE(object sender, EventArgs e)
{
    try
    {
        con.Open();
        using (SqlTransaction transaction = con.BeginTransaction())
        {
            auto();
            cmd = new SqlCommand("sp_insert_pdtl", con,transaction);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@purchase_id", textid.Text);
            cmd.Parameters.AddWithValue("@purchase_date", dateTimePicker1.Value);
            cmd.Parameters.AddWithValue("@ref_no", textrno.Text);
            for (int i = 0; i < datagrid.Rows.Count; i++)
            {
                cmd.Parameters.AddWithValue("@product_id", datagrid.Rows[i].Cells["product_id"].FormattedValue);
                cmd.Parameters.AddWithValue("@product_name", datagrid.Rows[i].Cells["product_name"].FormattedValue);
                cmd.Parameters.AddWithValue("@qty", datagrid.Rows[i].Cells["qty"].FormattedValue);
                cmd.Parameters.AddWithValue("@price", datagrid.Rows[i].Cells["price"].FormattedValue);
                cmd.Parameters.AddWithValue("@tax", datagrid.Rows[i].Cells["tax"].FormattedValue);
                cmd.Parameters.AddWithValue("@discount", datagrid.Rows[i].Cells["discount"].FormattedValue);
                cmd.Parameters.AddWithValue("@total", datagrid.Rows[i].Cells["total"].FormattedValue);
            }
            cmd.ExecuteNonQuery();
            transaction.Commit();
        }                        
        MessageBox.Show("Added Sucessfully", "OUTPUT", MessageBoxButtons.OK, MessageBoxIcon.Information);                           
    }
    catch (SqlException ex)
    {
        MessageBox.Show(ex.Message);
    } 

如何为两个不同表的文本框和数据网格视图值编写插入查询

在这里,您正在尝试插入一个主记录和多个子记录,这不能用您已经实现的方式来完成。它将只选择for循环返回的最后一个子记录,所有其他子记录都将被忽略。

我认为您应该将所有子记录作为XMLADO.NET表值参数传递给SP,并在SP中解析这些记录,然后插入到主记录之后。

对于表值ADO.NET参数,请检查以下链接。

使用ADO.Net 传递表值参数

还有一个建议,如果您在代码中使用截断,则在SP级别中不需要截断。