简体   繁体   中英

How To Delete Multiple Items from ListView C# With Delete Button

So, I have a simple ListView that users can add information to and a delete button that is only capable of deleting one selected item at a time. I'm trying to make it so that when multiple items are selected and 'delete' is pressed it deletes those selected items instead of just one. Your help is appreciated!

Add recipient code:

 private void addtoRecipients_Click(object sender, EventArgs e)
    {
        if (recipientEmailBox.Text != "")
        {
            string[] S = new string[4];
            S[0] = recipientEmailBox.Text;
            S[1] = recipientNameBox.Text;
            S[2] = txtLocation.Text;
            S[3] = txtSubject.Text;
            ListViewItem I = new ListViewItem(S);
            recipientBox.Items.Add(I);
            UpdateNoOfEmails();
        }
    }

My Delete Button Code (only deletes one selection at the moment)

 private void deleteEntryBTN_Click(object sender, EventArgs e)
    {
        try { recipientBox.Items.Remove(recipientBox.SelectedItems[0]); }

        catch { }
        UpdateNoOfEmails();
    }

Clear All Recipients Code

private void clearBTN_Click(object sender, EventArgs e)
    {
        recipientBox.Items.Clear();
        UpdateNoOfEmails();
    }

In my case, the simplest way to do it was with a while loop. This is what my new delete button code looks like:

 private void deleteEntryBTN_Click(object sender, EventArgs e)
    {
        try
        {
            while (recipientBox.SelectedItems.Count > 0)
            {
                recipientBox.Items.Remove(recipientBox.SelectedItems[0]);
            }
        }

        catch { }
        UpdateNoOfEmails();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM