zoukankan      html  css  js  c++  java
  • [转]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();
        }
      
    }
  • 相关阅读:
    android git问题File not found: git.exe
    asp.net 连接数据库的问题总结
    asp.net记账本
    asp.net对数据库增删改操作
    asp.net 连接数据库操作
    第九、十周周记
    作业四-兴趣问题清单
    价值观作业
    第七周周记
    第三次作业问卷调查
  • 原文地址:https://www.cnblogs.com/huige1004/p/1312292.html
Copyright © 2011-2022 走看看