C# WinForm ListView 多行删除 操作

说明:

Delete (删除按钮,从数据库中删除选中的记录)

Remove(移除按钮,仅从界面移除掉,未执行数据库删除操作)

代码只是做参考提供思路,未必你直接拷贝就能运行。

//Button Delete , delete selected items from database

private void buttonDelete_Click(object sender, EventArgs e)
{
    DialogResult dr = MessageBox.Show("Are you sure to delete selected items? ", this.Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
    if (dr == DialogResult.OK)
    {
        try
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();                               

                using (SqlCommand cmd = conn.CreateCommand())
                {
                    string sql = "";
                    string id = "";
                    foreach (ListViewItem item in this.listView1.SelectedItems)
                    {
                        id = item.SubItems[0].Text.Trim();// 0 is the index of id column in listView1
                        sql = string.Format("delete from users where id='{0}'", id); 
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = sql;
                        cmd.ExecuteNonQuery();
                    }
                }

                FreshData(conn);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString(), this.Text);
        }
    }
}



//Button Remove, remove selected items from listView1
private void buttonRemove_Click(object sender, EventArgs e)
{
    foreach (ListViewItem item in this.listView1.SelectedItems)
    {
        if (item.Selected)
        {
            item.Remove();
        }
    }
    this.listView1.Refresh();
}



//Function Fresh Data, write by your self

private void FreshData(SqlConnection conn)
{
}

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值