2 2 Votes

Delphi/Lazarus: Delete selected Items from ListBox using DEL-Key

Tip by Delphian | 09/01/2016 at 09:16

Today, I would like to show how to implement that a TListBox reacts to pressing the delete key (DEL) in Lazarus or Delphi and that accordingly, all selected entries will be removed from the list.

For that, we assign a OnKeyDown-Event to our listbox in which we are using the following code:

procedure TForm1.ListBox1KeyDown(Sender: TObject; var Key: Word; 
  Shift: TShiftState);
  i: integer;
  if key = $2E then begin

    for i := ListBox1.Items.Count - 1 downto 0 do begin
      if ListBox1.Selected[i] then ListBox1.Items.Delete(i);


The variable "Key" contains the pressed key. Because we want to react to the DEL key, first of all, we are asking whether the key is $2E. $2E is the virtual key code for the DEL key.

If yes, we are going through all items of the ListBox in order to delete them in the case that they are selected (in this case Selected[i] is TRUE). It is important to loop through the entries backwards (downto), because otherwise under circumstances we would access items in our loop that are no longer existing because we have deleted them before. we should use BeginUpdate and EndUpdate in order to ensure that the ListBox will not be repainted after each deletion.

00 Votes

Thank you!

This is the most helpful post that explains the simplest solution to delete items from a list - without getting access violations!
25/04/2018 at 13:24

ReplyPositive Negative
00 Votes

You do not need to do all this. Because:

23/10/2019 at 10:42

ReplyPositive Negative


Show Profile | Message
00 Votes

Of course, that's the easiest way.

But it depends on the Delphi and Lazarus version whether this function is already available. If someone is using older versions, he or she has to fall back to the manual solution.
23/10/2019 at 15:07

Positive Negative

About the Author

Avatar AuthorThe author has not added a short description to his profile yet.
Show Profile | Message


Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own articles on askingbox.com. How to do.