从datagridview中插入多个值到数据库

时间:2014-07-02 04:41:25

标签: datagridview sql-insert

有人可以帮我解决这段代码的问题吗?问题是“索引超出范围。必须是非负数且小于集合的大小。” :(

 try
            {



                OleDbConnection Con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\MotoFix.mdb;");
                Con.Open();

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


                    OleDbCommand Com = new OleDbCommand() { Connection = Con, CommandText = String.Format("INSERT INTO Transaction VALUES ('{0}' , '{1}' , '{2}' , '{3}' , '{4}', '(5)')", gridViewProduct_1.Rows[i].Cells[11].Value, gridViewProduct_1.Rows[i].Cells[7].Value, gridViewProduct_1.Rows[i].Cells[6].Value, gridViewProduct_1.Rows[i].Cells[8].Value, gridViewProduct_1.Rows[i].Cells[9].Value, gridViewProduct_1.Rows[i].Cells[10].Value) };
                    Com.ExecuteNonQuery();
                }

                Con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

1 个答案:

答案 0 :(得分:0)

for (int i = 0; i < gridViewProduct_Transac.Rows.Count; i++)
  {
   using (OleDbConnection Con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\MotoFix.mdb;"))
      {
      Con.Open();
      string str, strOrders;
      string strTranNo = gridViewProduct_Transac.Rows[ii].Cells[13].Value.ToString();
      string strCustomer = gridViewProduct_Transac.Rows[i].Cells[9].Value.ToString();
      string strReferral = gridViewProduct_Transac.Rows[i].Cells[11].Value.ToString();
      string strCashier = gridViewProduct_Transac.Rows[i].Cells[10].Value.ToString();
      string strOrder = gridViewProduct_Transac.Rows[i].Cells[8].Value.ToString();
      string strQuantity = gridViewProduct_Transac.Rows[i].Cells[6].Value.ToString();
      string strTotal = gridViewProduct_Transac.Rows[i].Cells[7].Value.ToString();
      string strDate = String.Format(gridViewProduct_Transac.Rows[i].Cells[12].Value.ToString(), "mm-DD-YYYY");
      string strprodNo = gridViewProduct_Transac.Rows[i].Cells[0].Value.ToString();
      Com_1.Connection = Con;
      strOrders = @"INSERT INTO [Order] (orderNo, prodCode) VALUES ('" + strOrder + "', '" + strprodNo + "')";
      using (Com_1 = new OleDbCommand(strOrders, Con))
         {
            Com_1.Parameters.AddWithValue(@"orderNo", strOrder);
             Com_1.Parameters.AddWithValue(@"prodCode", strprodNo);
             Com_1.ExecuteNonQuery();
          }

我已经解决了这个问题。这是代码:)