使用循环将数据网格视图选定行插入数据库

时间:2017-10-04 10:51:52

标签: c# sql-server winforms datagridview insert

我有一些数据应该插入到4个表中,其中一个数据存储在数据网格视图中选中的行,所以我会循环通过数据网格视图选择行将它们插入数据库我也用了一个方法做事务并将SqlCommands作为矩阵然后逐个进行,但是当我尝试插入数据时它会给我一个异常"索引超出范围。必须是非负的且小于集合的大小。"在这一行

cm[i].Parameters.Add("@car", Convert.ToInt32(newCarAdCarDgv.Rows[i].Cells[0].Value.ToString()));  

这是交易方法:

public void ExTr(SqlCommand[] cm)
{
    if (cn.State == ConnectionState.Closed)
    {
        cn.Open();
    }
    SqlTransaction tr = cn.BeginTransaction();
    for (int x = 0; x < cm.Length; x++)
    {
        cm[x].Connection = cn;
        cm[x].Transaction = tr;

    }

    try
    {
        for (int x = 0; x < cm.Length; x++)
        {
            cm[x].ExecuteNonQuery();
        }
        tr.Commit();
        MessageBox.Show("تمت عملية إضافة البيانات بنجاح");
    }
    catch (SqlException ex)
    {
        tr.Rollback();
        MessageBox.Show(ex.Message);

    }
    finally
    {
        if (cn.State == ConnectionState.Open)
        {
            cn.Close();
        }
    }

}

这是插入的代码:

private void newAdSaveBtn_Click(object sender, EventArgs e)
{
    try
    {
        count = newCarAdCarDgv.SelectedRows.Count + 3;
        if (cn.State == ConnectionState.Closed)
        {
            cn.Open();
        }

        newCarAdClientPhoneTxt_Leave(sender, e);
        newCarAdClientEmailTxt_Leave(sender, e);
        newCarAdNotesTxt_Leave(sender, e);

        SqlCommand[] cm = new SqlCommand[count];

        cm[0] = new SqlCommand("insert into clientData (Id,clientName,clientWork,clientPhone,clientMobile,clientEmail) values (@id,@name,@work,@phone,@mobile,@email)", cn);
        cm[0].Parameters.AddWithValue("@id", id);
        cm[0].Parameters.AddWithValue("@name", newCarAdClientNameTxt.Text.Trim());
        cm[0].Parameters.AddWithValue("@work", newCarAdClientWorkTxt.Text.Trim());
        cm[0].Parameters.AddWithValue("@phone", newCarAdClientPhoneTxt.Text.Trim());
        cm[0].Parameters.AddWithValue("@mobile", newCarAdClientMobileTxt.Text.Trim());
        cm[0].Parameters.AddWithValue("@email", newCarAdClientEmailTxt.Text.Trim());

        cm[1] = new SqlCommand("insert into marketingData (m_Id,marketingDurations,marketingStartsFrom,marketingEndsIn,notes,adDate) values (@id,@durations,@start,@end,@notes,@date)", cn);
        cm[1].Parameters.AddWithValue("@id", id);
        cm[1].Parameters.AddWithValue("@durations", newCarAdAdDurationTxt.Text.Trim());
        cm[1].Parameters.AddWithValue("@start", newCarAdStartDayDtp.Value);
        cm[1].Parameters.AddWithValue("@end", newCarAdEndDayDtp.Value);
        cm[1].Parameters.AddWithValue("@notes", newCarAdNotesTxt.Text.Trim());
        cm[1].Parameters.AddWithValue("@date", newCarAdDateDtp.Value);

        cm[2] = new SqlCommand("insert into priceAndProfits (p_Id,marketingCost,marketingPrice,marketingProfit,dollarPrice) values (@id,@cost,@price,@profit,@dollar)", cn);
        cm[2].Parameters.AddWithValue("@id", id);
        cm[2].Parameters.AddWithValue("@cost", newCarAdCostTxt.Text.Trim());
        cm[2].Parameters.AddWithValue("@price", newCarAdPriceTxt.Text.Trim());
        cm[2].Parameters.AddWithValue("@profit", newCarAdProfitTxt.Text.Trim());
        cm[2].Parameters.AddWithValue("@dollar", newCarAdDollarPriceTxt.Text.Trim());

        for (int i = 3; i <= newCarAdCarDgv.SelectedRows.Count + 3; i++)
        {
            cm[i] = new SqlCommand("insert into carWorkCount (c_Id,carId) value (@id,@car)", cn);
            cm[i].Parameters.Add("@id", id);
            cm[i].Parameters.Add("@car", Convert.ToInt32(newCarAdCarDgv.Rows[i].Cells[0].Value.ToString()));
        }

        ExTr(cm);

    }
    catch (SqlException ex)
    {
        MessageBox.Show(ex.Message);
    }
}

1 个答案:

答案 0 :(得分:0)

将最终循环更改为

for (int i = 0; i < newCarAdCarDgv.SelectedRows.Count; i++)
{
    cm[i+3] = new SqlCommand("insert into carWorkCount (c_Id,carId) value (@id,@car)", cn);
    cm[i+3].Parameters.Add("@id", id);
    cm[i+3].Parameters.Add("@car", 
      Convert.ToInt32(newCarAdCarDgv.SelectedRows[i].Cells[0].Value.ToString()));
}

您的代码引用了行[i],但我从值3开始,如果您选择网格中的所有行,则可以超出行数。相反,您只需要使用i + 3

引用命令