2014-12-03 88 views
-2

嗨,我正在尋找一種方法將所有我的GridView單元格或數據插入到SQL Server表中。我希望列匹配SQL Server的列和要添加的每一行。行總是在變化。這可能嗎?將GridView單元格或數據插入到SQL Server中

這是我曾嘗試(沒有錯誤,只是沒有做任何事情)

 foreach (GridViewRow GVRow in GridView1.Rows) 
     { 

      string PartNumber = string.Empty; 
      string Qty = string.Empty; 
      string Price = string.Empty; 
      string ExtPrice = string.Empty; 

      PartNumber = GVRow.Cells[1].Text; 
      Qty = GVRow.Cells[2].Text; 
      Price = GVRow.Cells[3].Text; 
      ExtPrice = GVRow.Cells[4].Text; 



      using (SqlConnection sqlCon5 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString)) 
      { 
       SqlCommand scm = new SqlCommand(); 
       scm.Connection = sqlCon5; 
       scm.CommandText = @"INSERT INTO OrderDetail (OrderNumber, PartNumber, Qty, Price, ExtPrice) VALUES (@OrderNumber, @PartNumber,@Qty,@Price,@ExtPrice)"; 

       scm.Parameters.AddWithValue("@OrderNumber", TextBox1.Text); 
       scm.Parameters.AddWithValue("@PartNumber", PartNumber.ToString()); 
       scm.Parameters.AddWithValue("@Qty", Qty.ToString()); 
       scm.Parameters.AddWithValue("@Price", Price.ToString()); 
       scm.Parameters.AddWithValue("@ExtPrice", ExtPrice.ToString()); 


       sqlCon5.Open(); 
       scm.ExecuteNonQuery(); 
       sqlCon5.Close(); 
      } 



     } 
+0

是的。你有什麼嘗試? – gabsferreira 2014-12-03 23:33:37

+0

我剛剛添加了我的代碼,我試過了,但它不起作用,它什麼都不做@bigodera – 2014-12-03 23:37:03

+0

什麼都不做?它是否達到了第一個「foreach」?是?它到底是什麼? – 2014-12-04 00:13:12

回答

0

嘗試使用for loop代替。

int rowsCount = GridView1.Rows.Count; 
int rowsInserted = 0; 

for (int i = 0; i < rowsCount; i++) 
{ 
    StrQuery = @"INSERT INTO OrderDetail (OrderNumber, PartNumber, Qty, Price, ExtPrice) VALUES (@OrderNumber, @PartNumber,@Qty,@Price,@ExtPrice)"; 
    scm.CommandText = StrQuery; 
    scm.Parameters.AddWithValue("@OrderNumber",GridView1.Rows[i]. 
         Cells["columnName"].Value); 
    scm.Parameters.AddWithValue("@PartNumber",GridView1.Rows[i]. 
         Cells["columnName"].Value); 
    scm.Parameters.AddWithValue("@Qty",GridView1.Rows[i]. 
         Cells["columnName"].Value); 
    scm.Parameters.AddWithValue("@Price",GridView1.Rows[i]. 
         Cells["columnName"].Value); 
    scm.Parameters.AddWithValue("@ExtPrice",GridView1.Rows[i]. 
         Cells["columnName"].Value); 

if (scm.ExecuteNonQuery() > 0) 
{ 
    rowsInserted++; 
} 
scm.Parameters.Clear(); 
} 

//check if all rows inserted 
if(rowsCount == rowsInserted) 
{ 
    //Display successfull message 
} 
else 
{ 
    //Display error message 
} 

注:*與GridView1實際的列名替換columnName

+0

我得到無效的參數,你輸入列名 – 2014-12-04 00:27:37

+0

Nevermind my code worked lol – 2014-12-04 00:42:27

相關問題