简体   繁体   中英

Prevent Certain Items from Being Deleted in ListBox

So here is the code I have the allows me to delete selected items in my listbox.

    ListBox.SelectedObjectCollection selectedItems = new ListBox.SelectedObjectCollection(lstOutput);
    selectedItems = lstOutput.SelectedItems;

    if (lstOutput.SelectedIndex != -1)
    {
        for (int i = selectedItems.Count - 1; i >= 0; i--)
            lstOutput.Items.Remove(selectedItems[i]);
    }
    else
        MessageBox.Show("Debe seleccionar un email");

The problem is that I have labels at the top that show what the output is. I also have statistics at the bottom of the page. The way the code is now, I am able to delete those, which I don't want. I am unsure of how to prevent these from being deleted.

first of all the fire line is unneeded and you can merger the two first line to:

ListBox.SelectedObjectCollection selectedItems = lstOutput.SelectedItems;

now for the remove of the item that you want to keep. you can make a condition.

for (int i = selectedItems.Count - 1; i >= 0; i--)
{
     if(selectedItems[i] is /*here is where you come and check if the current selected item is of the type you don't want to delete*/)
            lstOutput.Items.Remove(selectedItems[i]);
}

if you'll tell me what's the type of the "labels at the top" and "statistics at the bottom" i'll put it in the answer

EDIT

in similar to what you said you can do:

List<object> fixedItems = new List<object>();
fixedItems.Add(/*Your labels and statistics*/);

and then do

for (int i = selectedItems.Count - 1; i >= 0; i--)
{
     if(fixedItems.Contains(selectedItems[i]) == false)
            lstOutput.Items.Remove(selectedItems[i]);
}

for the list you'll need to add

using System.Collections.Generic;

at the beginning of the page

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