2014-10-03 50 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); 
       } 

      } 
相关问题