Question

I’m trying to replace a "comma" with "comma + space" using the following code in a procedure called by the OnChange Event on a RichEdit control in Delphi 2010.

SomeString := RichEdit.Lines.Strings[RichEdit.Lines.Count-1];
Position  := Pos(',', SomeString);
if Position > 0 then
begin
  Delete(SomeString, Position, 1);
  Insert(', ',  SomeString, Position);
  RichEdit.Lines.Strings[RichEdit.Lines.Count-1] := SomeString;
end;

It works perfectly, but I can’t use BACKSPACE and DEL via keyboard anymore (on the RichEdit Control), because the inserted characters act like barriers. It doesn’t happen with another set of inserted characters, only with "comma + space".

Can someone tell me what am I doing wrong here ?

Was it helpful?

Solution

Just try this code

  //get the string
  SomeString := RichEdit.Lines.Strings[RichEdit.Lines.Count-1];
  //replace the 'comma' with 'comma+space'
  SomeString :=StringReplace(SomeString ,',',', ',[rfReplaceAll,rfIgnoreCase]);
  //now delete the extra space which gets added each time you call this event
  SomeString :=StringReplace(SomeString ,',  ',', ',[rfReplaceAll,rfIgnoreCase]);
  //your desired result
  RichEdit.Lines.Strings[RichEdit.Lines.Count-1] := SomeString ;

Remember the BACKSPACE and DEL are working fine. But in case of your code there was an extra space added each time you try and change the contents of RichEdit. Hence giving an impression of the 2 keys not working.

Since you are having problems deleting the space in front of comma I will provide with another solution

Add a Boolean variable to the class isComma: Boolean.
Later on OnKeyPress event of RichEdit inset this code

  isComma := False;
  if key = ',' then
    isComma := True;

OnChange event code goes here

var
  CurPoint: TPoint;
  cText: string;
  cLine: string;
begin
  if isComma then
  begin
    cLine:=' ';   //character to be added after comma, ' ' in here
    CurPoint:=RichEdit1.CaretPos;
    cText:=RichEdit1.Lines.Strings[CurPoint.y];
    //add ' ' where the cursor is i.e. after the comma
    cText:=Copy(cText,0,CurPoint.x)+cLine+Copy(cText,CurPoint.x+1,Length(cText));
    RichEdit1.Lines.Strings[CurPoint.y]:=cText;
  end;
end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top