【问题标题】:removing rows from datagridview after insert them to database将行插入数据库后从datagridview中删除行
【发布时间】:2014-10-09 22:34:16
【问题描述】:

我编写了一个程序,可以将不同事物的条形码插入数据库。 首先,如果用户单击按钮后,我将所有条形码添加到 datagridview 中,所有条形码都从 datagridview 插入数据库。

在将每个条形码插入数据库之前,我会检查它是否有重复。

当每个条形码插入数据库时​​,我想从 datagridview 中删除每个条形码。

但它不能正常工作

它只是将其中一些插入到数据库中,其中一些留在数据网格视图中 这是它的代码:

         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();
    }

【问题讨论】:

  • 如果您希望在 foreach 完成后删除所有行,只需在循环完成后调用 dataGridView1.Rows.Clear();。你对dataGridView1.Rows.Remove(row); 的调用无论如何都会失败,因为你正在修改你正在迭代的集合。
  • 您可能还想parametrize您的 SQL 查询。

标签: c# sql datagridview c#-3.0


【解决方案1】:

两天前我遇到了同样的问题... 实际上我的程序做得很好。希望对您有所帮助:

            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);
              }

            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多