【问题标题】:how to insert the database multiple gridview choises如何插入数据库多个gridview选项
【发布时间】:2016-12-27 18:42:47
【问题描述】:
  siparisDetayy order = new siparisDetayy();
    public void gridControl()
    {       
        for (int i = 0; i < dtGridSiparis.RowCount-1; i++)
            {
            order.productID =(dtGridSiparis.Rows[i].Cells[0].Value).ToString();
            order.productName = dtGridSiparis.Rows[i].Cells[1].Value.ToString();
            order.customer = dtGridSiparis.Rows[i].Cells[2].Value.ToString();
            order.faturaNo = dtGridSiparis.Rows[i].Cells[3].Value.ToString();
            order.miktar = dtGridSiparis.Rows[i].Cells[4].Value.ToString();
            order.price = dtGridSiparis.Rows[i].Cells[5].Value.ToString();
            }
            ctx.siparisDetayys.InsertOnSubmit(order);
            ctx.SubmitChanges();
    }

我尝试使用 LINQ 插入我的数据库中的所有数据,即使我做了 for 循环但仍然只添加了一行。

【问题讨论】:

  • 我清楚地看到您只插入一个对象,尝试一个对象集合,然后使用循环/linq 或其他方式将它们全部插入。
  • order.price 是字符串吗?

标签: c# sql linq datagridview


【解决方案1】:

Rahul 所说的,还要加上第一行“siparisDetayy order = new siparisDetayy();”循环内。您必须为每一行创建一个新实体。

【讨论】:

  • 非常感谢
【解决方案2】:

是的,这是因为您实际上只插入了一条 order 记录,并且希望是您从循环最后一次迭代中收集的最后一条记录。将保存移动到循环内的数据库代码行,如下所示

    for (int i = 0; i < dtGridSiparis.RowCount-1; i++)
        {
        order.productID =(dtGridSiparis.Rows[i].Cells[0].Value).ToString();
        order.productName = dtGridSiparis.Rows[i].Cells[1].Value.ToString();
        order.customer = dtGridSiparis.Rows[i].Cells[2].Value.ToString();
        order.faturaNo = dtGridSiparis.Rows[i].Cells[3].Value.ToString();
        order.miktar = dtGridSiparis.Rows[i].Cells[4].Value.ToString();
        order.price = dtGridSiparis.Rows[i].Cells[5].Value.ToString();

        //Save or Insert the record to database
        ctx.siparisDetayys.InsertOnSubmit(order);
        ctx.SubmitChanges();
        }

【讨论】:

  • 是的,我已经完成了,但它显示错误消息:“无法添加已经存在的实体。”
  • @ZulfikarBakır,是的,如果您的网格行重复,因为您没有检查它。好吧,这是一个单独的问题,因此单独发布。
猜你喜欢
  • 2015-02-02
  • 1970-01-01
  • 1970-01-01
  • 2023-02-03
  • 2019-07-31
  • 1970-01-01
  • 1970-01-01
  • 2022-07-28
  • 1970-01-01
相关资源
最近更新 更多