[转]DataGridView批量删除

 

要实现如图所示的批量删除:


第一列为程序动态添加的CheckBox列,关键的两个函数为:
1 数据填充函数:
private void fillIt()
{
    dataGridView1.Columns.Clear();
    SqlConnection conn = new SqlConnection("server=.;database=daily;uid=sa;pwd=123456");
    conn.Open();
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = new SqlCommand();
    da.SelectCommand.Connection = conn;
    da.SelectCommand.CommandType = CommandType.Text;
    da.SelectCommand.CommandText = "select * from sceret";
    da.Fill(ds,"sceret");
    dataGridView1.DataSource = ds.Tables["sceret"];
    DataGridViewCheckBoxColumn newColumn = new DataGridViewCheckBoxColumn();
    dataGridView1.Columns.Insert(0,newColumn);
    conn.Close();
}

2 删除按钮触发事件:
private void btnDel_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection("server=.;database=daily;uid=sa;pwd=123456");
    conn.Open();
    string delStr = "(";
    for (int i = 0; i < Convert.ToInt32(dataGridView1.RowCount); i++)
    {
        if (Convert.ToBoolean(dataGridView1[0, i].Value))
        {
            delStr += dataGridView1[1, i].Value.ToString() + ",";
        }
    }
    if (delStr == "(")
    {
        MessageBox.Show("没有需要删除的项");
    }
    else
    {
        delStr = delStr.Substring(0, delStr.Length - 1) + ")";
        delStr = "delete sceret where id in" + delStr;
        SqlCommand cmd = new SqlCommand(delStr, conn);
        cmd.ExecuteNonQuery();
        fillIt();
    }
  
}

posted on 2008-10-16 08:33  小灰熊  阅读(655)  评论(0)    收藏  举报

导航