Home
Manage Your Code
Snippet: Remove 1 or multiple items from a listbox gracefully (don't lose place) good for long lists (C#)
Title: Remove 1 or multiple items from a listbox gracefully (don't lose place) good for long lists Language: C#
Description: Removes items from a list box and remembers your approximate placement in the list so if the list if very long you don't lose your place everytime you delete entries. Windows forms. Views: 637
Author: Garth Sweet Date Added: 2/28/2008
Copy Code  
1        /// <summary>
2        /// Removes the selected item(s) from list box.
3        /// All seleted items (can be zero, 1 or many) will be removed from the list.
4        /// User will be left with a single item in the list selected that will be either the item in
5        /// the list immediately preceeeding the first item removed or the first item in list.
6        /// </summary>
7        /// <param name="targetListBox">The list box to remove selected items from</param>
8        private void RemoveSelectItemsFromListBox(ListBox targetListBox)
9        {
10            if (targetListBox != null && targetListBox.SelectedItems.Count > 0)
11            {
12                // Remember the item in the list that immediately preceeds the 
13                // selected item. After the sleected item(s) are deleted this entry
14                // will be made the selected item. This is nice when the user
15                // has potentially 100's of entries in thier list and deletes one. It prevents
16                // them springing back to the top of the list and losing thier place. 
17                object focusItem = null;
18                if (targetListBox.SelectedIndex > 0)
19                    focusItem = targetListBox.Items[targetListBox.SelectedIndex - 1];
20
21                // Remove each selected item
22                while (targetListBox.SelectedItems.Count > 0)
23                    targetListBox.Items.Remove(targetListBox.SelectedItem);
24
25                // If your form only lights up the save button on changes in data
26        // light it up here
27                // SetDataDirty(true);
28
29                // Go to the focus item in the list (or the top item if the focus item isn't available)
30                if (focusItem != null && targetListBox.Items.Contains(focusItem))
31                    targetListBox.SelectedItem = focusItem;
32                else if (targetListBox.Items.Count > 0)
33                    targetListBox.SelectedIndex = 0;
34
35            }
36        }
Usage
RemoveSelectItemsFromListBox(lstUsers);
// No exception handling in it but should handle all typical mistakes / scenarios as is.
Notes
Questions/Comments: Bitmugger@gmail.com