日期:2014-05-18  浏览次数:20775 次

datagridview删除多行数据
C#中在一个窗体中有一个datagridview1控件 里面datagridview1.DataSource = operdb.strdt("SELECT 序号,员工编号,单位,姓名 from tb1);
tb1表中序号是唯一的,记录有上千条,我需要的是在datagridview1控件中选中多行,点删除后,就执行 "delete tb1 where 序号=" + datagridview1[0, datagridview1.CurrentCell.RowIndex].Value.ToString()" 在数据库中删除该条语句
然后再datagridview1.DataSource = operdb.strdt("SELECT 序号,员工编号,单位,姓名 from tb1);重新加载datagridview1数据, 现在问题是我如何使用循环在数据库中一条一条的删除我在datagridview1中选中的多行数据.

------解决方案--------------------
DataGridViewCheckBox选择删除
foreach (DataGridViewRow dr in this.dataGridView1.Rows)
{
DataGridViewCheckBoxCell cbx = (DataGridViewCheckBoxCell)dr.Cells[0];
if ((bool)cbx.FormattedValue)
{
}
}

------解决方案--------------------
delete 表名 where 字段 in (id,id,id,id,id)

这样也可以
不过你要传你要删除行的id
------解决方案--------------------
如果你是用DataGridViewCheckBox选择的话就用2楼的方法
如果dataGridView允许多行选择的话,就试下以下方法。
C# code

            SqlCommand cmd = new SqlCommand(string.Empty, sqlcon);
            SqlTransaction tran = cmd.Transaction;
            try
            {
                for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
                {
                    cmd.CommandText = "delete tb1 where 序号=" + dataGridView1.SelectedRows[i].Cells[0].ToString();
                    cmd.ExecuteNonQuery();
                }
                tran.Commit();
                MessageBox.Show("删除成功!  ", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch(Exception ex)
            {
                tran.Rollback();
                MessageBox.Show("删除失败!  " + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }