Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Items from ListView in C#

Tags:

c#

listview

I need to delete items from a ListView, the code I am looking for will show a MessageBox to confirm and if no item is selected it will show an error MessageBox

This is my code and it is not working :(

private void button2_Click(object sender, EventArgs e)
{
    if (listView1.SelectedItems != null)
    {
        var confirmation = MessageBox.Show(
            "Voulez vous vraiment supprimer les stagiaires séléctionnés?",
            "Suppression", MessageBoxButtons.YesNo, MessageBoxIcon.Question
        );

        if (confirmation == DialogResult.Yes)
        {
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                if (listView1.Items[i].Selected)
                {
                    listView1.Items[i].Remove();
                    i--;
                }
            }
        }
    }
    else
    {
        MessageBox.Show("aucin stagiaire selectionnes", "erreur",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

The error is not in delete but, in MessageBox's I have two MessageBox's, error must be shown first before confirmation.

like image 691
mabezat Avatar asked Mar 22 '13 13:03

mabezat


People also ask

How to remove items from ListView?

To remove items programmaticallyUse the RemoveAt or Clear method of the Items property. The RemoveAt method removes a single item; the Clear method removes all items from the list.

How to remove item from ListView in android studio?

Android App Development for Beginners In the above code, we have taken name as Edit text, when user click on save button it will store the data into arraylist. Click on delete button to delete the record from listview.


1 Answers

Start counting from the end going to zero

for (int i = listView1.Items.Count - 1; i >= 0; i--)
{
    if (listView1.Items[i].Selected)
    {
        listView1.Items[i].Remove();
    }
}

However consider that every ListViewItem has an Index property and you can use it with the SelectedItems collection in such a way to prepare a solution that has the advantages to avoid a redundant test and a loop on lesser number of items.

Also, the SelectedItems collection is never null, if no selection is present, then the collection is empty but not null.

So your code could be rewritten

if (listView1.SelectedItems.Count > 0)
{
    var confirmation = MessageBox.Show("Voulez vous vraiment supprimer les stagiaires séléctionnés?", "Suppression", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if (confirmation == DialogResult.Yes)
    {
        for (int i = listView1.SelectedItems.Count - 1; i >= 0; i--)
        {
            ListViewItem itm = listView1.SelectedItems[i];
            listView1.Items[itm.Index].Remove();
        }
    }
}
else
    MessageBox.Show("aucin stagiaire selectionnes", ...);
like image 178
Steve Avatar answered Sep 29 '22 04:09

Steve