Search code examples
delphitmemo

How to delete a line found by text from a TMemo control?


I'm having a TEdit, TMemo and a button. When the user presses the button, I want to delete from that memo control a line matching the text entered in the edit box. If no matching line is found, some sort of "line not found" message should be displayed.

I'm new to Delphi and don't know any code for this, but in theory it should work on the principle of searching the TMemo until it finds a line that matches Edit.Text and then deletes that specific line.

Could someone show me how to delete a line found by text from a TMemo control?


Solution

  • Use the IndexOf function to find the index of an item by text in a string list. If this function returns value different from -1, the string was found and you can delete it from the list by using the Delete method passing the found index:

    var
      Index: Integer;
    begin
      Index := Memo.Lines.IndexOf(Edit.Text);
      if Index <> -1 then
        Memo.Lines.Delete(Index)
      else
        ShowMessage('Text not found!');
    end;
    

    Note, that the IndexOf function is case insensitive.