简体   繁体   English

如何使用删除按钮从ListView C#中删除多个项目

[英]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. 因此,我有一个简单的ListView,用户可以向其中添加信息,还有一个删除按钮,该按钮只能一次删除一个选定的项目。 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. 就我而言,最简单的方法是使用while循环。 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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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