2014-02-19 16 views
-3

我想插入所有datagridview的數據插入按鈕數據庫表中單擊如何從DataGridView插入的所有數據以數據庫表上按一下按鈕在C#

private void cs_btnfinish_Click(object sender, EventArgs e) 
    { 
     string StrQuery; 

     for (int i = 0; i < dataGridView1.Rows.Count; i++) 
     { 
      StrQuery = "INSERT INTO tblmedisale VALUES ('" + dataGridView1.Rows[i].Cells[0].Value + "', '" + Convert.ToDecimal(dataGridView1.Rows[i].Cells[1].Value) + "', '" + Convert.ToDecimal(dataGridView1.Rows[i].Cells[2].Value) + "')"; 
      con.Open(); 
      SqlCommand cmd = new SqlCommand(StrQuery, con); 
      cmd.ExecuteNonQuery(); 
      con.Close(); 
     } 

     MessageBox.Show("aaaa"); 
    } 

enter image description here

+2

你究竟有什麼問題? 'con'從哪裏來?你不需要在每次迭代時打開和關閉它,只需在循環之前打開一次,然後關閉它(使用'using')即可。此外,你很容易發生SQL注入攻擊,應該使用預處理語句。 –

+1

你有什麼問題?你也應該使用參數化查詢來防止SQL注入 –

回答

0

試試這個:

private void inserttoDatagridview() 
     { 
      try 
      { 
       con.Open() 
       (foreach GridViewRow rw in DataGridView1.Rows) 
       { 
        cmd = New SqlCommand("insert into tblEmp (empid,empname,empdesg,dob) values (" & rw.Cells(0).Value & ",'" & rw.Cells(1).Value & "','" & rw.Cells(2).Value & "','" & CDate(rw.Cells(3).Value.ToString()) & "') ", con); 
        cmd.ExecuteNonQuery(); 
       } 

      } 
      catch (Exception ex) 
      { 
       throw; 
      } 
      finally 
      { 
       con.Close() 
      } 
     } 
0
myconn = New SqlConnection("server=DESKTOP-49GM42J;DATABASE=BAC Billing_System;Trusted_Connection=true") 
    myconn.Open() 

    For Each rw As DataGridViewRow In DataGridEffectData.Rows 

     mycmd = New SqlCommand("insert into AllProducts (ProductID,ProductName,UnitPrice,ItemsLeft) values ('" & rw.Cells(0).Value & "','" & rw.Cells(1).Value & "','" & rw.Cells(2).Value & "','" & (rw.Cells(3).Value) & "') ", myconn) 
     mycmd.ExecuteNonQuery() 

    Next 
    myconn.Close() 

這是幾乎相同的代碼在vb.net.my問題是它創建一個空白行貝爾每當我使用這個命令通過dataGridView向數據庫中插入一行數據。

0

做空行檢查在循環中一個GridView執行INSERT前:

Private void inserttoDatagridview() 
     { 
      try 
      { 
       con.Open() 
       (foreach GridViewRow rw in DataGridView1.Rows) 

if rw.Cells(0) <> Nothing then 
       { 
        cmd = New SqlCommand("insert into tblEmp (empid,empname,empdesg,dob) values (" & rw.Cells(0).Value & ",'" & rw.Cells(1).Value & "','" & rw.Cells(2).Value & "','" & CDate(rw.Cells(3).Value.ToString()) & "') ", con); 
        cmd.ExecuteNonQuery(); 

End If 
       } 

     } 
     catch (Exception ex) 
     { 
      throw; 
     } 
     finally 
     { 
      con.Close() 
     } 
    } 
相關問題