Search code examples
.nettextrichtextboxdelphi-prismindexoutofboundsexception

How to append and read text line per line with RichTextBox?


I have a richtextbox on a winform and would like to append and read text line per line.

Take a look at my attempt in my code as follows:

method ScriptDlgpas.Execute(memo:RichTextBox): Boolean;
var i:Integer;
begin
  Result := false;

  scriptMemo.Clear;
  var line1 := memo.Lines;
  while (line in line1) do
    scriptMemo.AppendText(line);

  if ShowDialog = DialogResult.OK then
  begin
    memo.Clear;
    var line2 := ScriptMemo.Lines;
    while(line in line2) do
        memo.AppendText(line);
    Result := true;
  end;
end;

I have two richtextbox, scriptmemo and memo. I set text to scriptmemo and then I read that back out to append to memo RichTextBox. It all seems logical and of course it compiles successfully, but compiler raises exception, IndexOutofRange, during runtime for the line var line1 := memo.Lines

Any help will be appreciated. Thanks,


Solution

  • From the looks of it, either fellow programmers don't know what I am talking about or have no clue how to solve it.

    I did figure out my problem and would like to post the answer in the hope it will help others.

    Here is the revised and working code:

    method ScriptDlgpas.Execute(memo:RichTextBox): Boolean;
    var i:Integer;
        lines1, lines2 : Array of string;
    begin
      Result := false;
    
      scriptMemo.Clear;
      lines1 := memo.Lines;
      for each aline in lines1 do
      begin
        scriptMemo.AppendText(aline+System.Environment.NewLine);
      end;
    
      if ShowDialog = DialogResult.OK then
      begin
        memo.Clear;
        lines2 := ScriptMemo.Lines;
        for each aline in lines2 do
        begin
            memo.AppendText(aline+System.Environment.NewLine);
        end;
        Result := true;
      end;
    end;