1

Hi I am building an invoice project using a TStringGrid to enter data (I am using a grid to keep the individual items and their amounts aligned). Because of the size of the final report I am limiting each row length to 47 characters and after that the next row will receive the onKeyUp event. This is easy to do

procedure TForm1.ngridKeyUp(Sender: TObject; var Key: Word;
   Shift: TShiftState);
var
  s, s2:string;
  p, l:Integer;
begin
  if Length(ngrid.Cells[ngrid.col,ngrid.row]) =47 then 
  ngrid.Row:=ngrid.Row+1;
end;

Code splits a word

But I don't want to split a word so I find the last space, trim the cell text to that point and put the remainder on the next line

procedure TForm1.ngridKeyUp(Sender: TObject; var Key: Word;
   Shift: TShiftState);
var
  s, s2:string;
  p, l:Integer;
begin
  if Length(ngrid.Cells[ngrid.col,ngrid.row]) =47 then
    begin
      s:= ngrid.Cells[ngrid.col,ngrid.row];
      l:= Length(s);
      p:=LastDelimiter(' ',s);
      s2:=RightStr(s,l-p);
      ngrid.Cells[ngrid.col,ngrid.row]:=LeftStr(s,p);
      ngrid.Row:=ngrid.Row+1;
      ngrid.cells[ngrid.col,ngrid.row]:=s2;
    end;
end;

This works

The word is moved down

but the text in the new cell must be selected because the next character typed clears the cell. Like so

Cell text cleared

How do I stop the cell text being selected or move the cursor to the end?

Learning
  • 129
  • 1
  • 8
  • 1
    Your approach of how to deal with your problem has several flaws. First flaw is that you decide when to go into the next line based on the string character count but you are not using font whose characters don't all have same width. Width of a string containing 47 `I` characters is much smaller than a text containing 47 `W` characters for instance. Also how do intent of dealing when users starts deleting the text once it was already split across multiple cells? Especially if the user goes and starts changing text in the first cell. – SilverWarior Jun 10 '22 at 11:19
  • 1
    Have you perhaps considered enabling string grid cells to show text split into multiple lines like it is shown in [How to put CR/LF into a TStringgrid cell?](https://stackoverflow.com/a/13045940/3636228)? – SilverWarior Jun 10 '22 at 11:21
  • 1
    TStringGrid might not be the best solution to this problem. For instance, maybe a TFlowPanel holding TMemo controls, or a similar container setup, might be more appropriate. – Remy Lebeau Jun 10 '22 at 15:12

1 Answers1

1

Following up on SilverWarrior's advice, I located a stringgrid with multiline cell properties. ZColorStringGrid v.0.3 avaiable from Torry's Delphi Pages (Freeware) solved my problem and still kept items and amounts aligned. So thank you for the inspiration. I am slightly disappointed that no-one answered my actual question - it would have been useful in the future.

Learning
  • 129
  • 1
  • 8