user2781018
user2781018

Reputation:

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.

Upvotes: 1

Views: 181

Answers (1)

No Idea For Name
No Idea For Name

Reputation: 11577

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

Upvotes: 1

Related Questions