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.
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.
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.
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", ...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With