33 Votes

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

Tip by Delphian | 2016-01-09 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);
var
  i: integer;
begin
  if key = $2E then begin
    Listbox1.Items.BeginUpdate;

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

    ListBox1.Items.EndUpdate;
  end;
end;

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.

ReplyPositiveNegativeDateVotes
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!
2018-04-25 at 13:24

ReplyPositive Negative
11 Vote

You do not need to do all this. Because:

ListBox1.DeleteSelected;
2019-10-23 at 10:42

ReplyPositive Negative
11 Vote

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.
2019-10-23 at 15:07

Positive Negative
Reply
Reply

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

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.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.