首页 > 代码库 > C# WinForm listView 多行删除 操作

C# WinForm listView 多行删除 操作

//Button Delete , delete selected items from databaseprivate 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 listView1private 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 selfprivate void FreshData(SqlConnection conn){}

 

C# WinForm listView 多行删除 操作