C#: How to delete item from listbox using keyboard 'delete' button?

Hello,

 I would like to know how to delete an item from a listbox using the keyboard. For example, a listbox lives on a form and has some items in it. The user selects an item (single select mode). The user then types "delete" (a key press) on the keyboard. The item is then deleted from the listbox.


Thanks!
Tom
embalismAsked:
Who is Participating?
 
Anurag AgarwalConnect With a Mentor Python DeveloperCommented:
Hi you can use either keypress or keyup events of listbox for capturing the keyboard events

private void listbox_keyUp(object sender, KeyUpEventArgs e)
 {

       if (e.KeyCode == Keys.Delete)
      {
          //remove selected item from list
      }
 }

Anurag
0
 
embalismAuthor Commented:
Thanks, that did the trick!

I created a static class to handle the removal (to help anyone else who has this issue). See code attachment. It also supports MoveUp, MoveDown, and Delete for any of your domain lists.



        public static void MoveUp(ListBox listBox, IList items)
        {
            if (listBox.SelectedIndex < 0)
                return;
 
            if (listBox.SelectedIndex == 0 || listBox.Items.Count < 2)
                return;
 
            var tempItem = items[listBox.SelectedIndex - 1];
            items[listBox.SelectedIndex - 1] = items[listBox.SelectedIndex];
            items[listBox.SelectedIndex] = tempItem;
 
            show(listBox, items);
        }
 
        public static void MoveDown(ListBox listBox, IList items)
        {
            if (listBox.SelectedIndex < 0)
                return;
 
            if (listBox.SelectedIndex == listBox.Items.Count - 1 ||
                listBox.Items.Count < 2)
                return;
 
            var tempItem = items[listBox.SelectedIndex + 1];
            items[listBox.SelectedIndex + 1] = items[listBox.SelectedIndex];
            items[listBox.SelectedIndex] = tempItem;
 
            show(listBox, items);
        }
 
        public static void Delete(ListBox listBox, IList items)
        {
            if (listBox.SelectedIndex > -1)
                items.RemoveAt(listBox.SelectedIndex);
            else
                return;
 
            show(listBox, items);
        }
 
        private static void show(ListBox listBox, IList items)
        {
            listBox.Items.Clear();
            foreach (var item in items)
                listBox.Items.Add(item);
        }
    }

Open in new window

0
 
embalismAuthor Commented:
Thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.