2014-10-03 51 views
0

我編寫了一個程序,將不同事物的條形碼插入到數據庫中。 首先,我將所有條形碼添加到datagridview後,如果用戶單擊按鈕,所有條形碼從datagridview插入到數據庫。在將數據插入到數據庫之後從datagridview中刪除行

每個條形碼插入數據庫之前我檢查它是否有重複。

我想從datagridview中刪除每個條形碼,當他們每個插入到數據庫。

,但它不正常工作

它只需插入他們中的一些DATABSE,其中一些AER留在數據網格視圖 這裏是它的代碼:

  Cnn.Open(); 
     foreach (DataGridViewRow row in dataGridView1.Rows) 
     { 
      SqlCommand cm = new SqlCommand("select BarcodeId from Bought_Product where BarcodeId='" + row.Cells[1].Value.ToString() + "'", Cnn); 
      SqlDataReader dr = cm.ExecuteReader(); 
      if (dr.HasRows) 
      { 
       while (dr.Read()) 
       { 
        MessageBox.Show(dr[0].ToString() + "تکراری می باشد"); 

       } 
       dr.Close(); 
      } 
      else 
      { 

       dr.Close(); 
       SqlCommand cmd2 = new SqlCommand("insert into Bought_Product (Persons_Id,Bought_Date,Bought_fac_num,BarcodeId) values ('" + textBox3.Text + "','" + textBox2.Text + "','" + textBox1.Text + "','" + row.Cells[1].Value.ToString() + "')", Cnn); 
       cmd2.ExecuteNonQuery(); 
       MessageBox.Show(row.ToString()); 
       dataGridView1.Rows.Remove(row); 
      } 
     } 
     Cnn.Close(); 
    } 
+0

如果你想一次在foreach已經完成了被刪除的所有行只需要調用'dataGridView1.Rows.Clear();'循環完成後。你對'dataGridView1.Rows.Remove(row);'的調用無論如何都會失敗,因爲你正在修改你正在迭代的集合。 – 2014-10-03 11:39:42

+0

看到這個http://stackoverflow.com/questions/15403231/gridview-delete-row – Kishan 2014-10-04 08:30:05

+0

你可能還想[參數化](https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet)你的SQL查詢。 – smr5 2014-10-09 14:40:26

回答

0

我得到了同樣的問題2天前... 其實我的程序做得很好。願這可以幫助你:

  if (MessageBox.Show("Delete this Row?", "Löschen", MessageBoxButtons.YesNo) == DialogResult.Yes) 
      { 
       if (!this.dataGridView1.Rows[this.rowIndex].IsNewRow) 
       { 
       this.dataGridView1.Rows.RemoveAt(this.rowIndex); 
       } 

      } 
相關問題