简体   繁体   English

Linq to SQL插入存储过程从插入中排除第一行

[英]Linq to SQL insert stored procedure exclude first row from inserting

I have a stored procedure in SQL Server responsible for inserting records into the database: 我在SQL Server中有一个存储过程,负责将记录插入数据库:

ALTER proc [dbo].[Sp_Add_Item_Decription]
    @orderid int,
    @itemid int,
    @qty decimal(18, 2),
    @price decimal(18, 2)
as
    insert into [ResturantDB].[dbo].[ItemDescribtion] ([OrderID], [ItemID],[Qty], [Price])
    values (@orderid, @itemid, @qty, @price)

I used Linq to SQL to generate the below code but when I execute this code, if the datagridview contains one row it isn't inserted into the database, but if the datagridview contains more than one record then all records are inserted except the first row. 我使用Linq to SQL生成以下代码,但是当我执行此代码时,如果datagridview包含一行,则不会将其插入数据库中,但是如果datagridview包含多个记录,则将插入除第一行以外的所有记录。 I don't know what is the problem. 我不知道是什么问题。 I need to insert all the datagridview records. 我需要插入所有的datagridview记录。

private void Button3_Click(object sender, EventArgs e)
{
    dataGridView1.DataSource = DTL;

    if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox3.Text))
    {
        for(int i = 0; i < dataGridView1.Rows.Count - 1; i++)
        {
            resturantDataContext addorderdes = new resturantDataContext();
            addorderdes.Sp_Add_Item_Decription(Convert.ToInt32(textBox1.Text),
                               Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value),
                               Convert.ToDecimal(dataGridView1.Rows[i].Cells[3].Value),
                               Convert.ToDecimal(dataGridView1.Rows[i].Cells[4].Value));
            addorderdes.SubmitChanges();
        }

        RadMessageBox.Show("RECORD ADDED!");
    }
}

Instead of 代替

for(int i = 0; i < dataGridView1.Rows.Count - 1; i++)
        {

use 采用

for(int i = 0; i < dataGridView1.Rows.Count; i++)
        {

In this way you get the last row too. 这样,您也可以获得最后一行。

Your loop termination is on: 循环终止已打开:

i < dataGridView1.Rows.Count - 1;

This will always be one less than the number of rows in the data grid. 这将始终比数据网格中的行数少一。

Just replace it with: 只需将其替换为:

i < dataGridView1.Rows.Count;

Also as Adrian Iftode points out in his comment you don't need to recreate the context on every iteration of the loop and you don't need to call SubmitChanges as your stored procedure is writing the data directly back to the database. 同样,正如Adrian Iftode在其注释中指出的那样,您不需要在循环的每次迭代中都重新创建上下文,也不需要调用SubmitChanges因为您的存储过程SubmitChanges数据直接写回到数据库中。

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

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