When I finish entering the value in a cell of the TStringGrid I need to check if it is greater than the value that is in the cell of the previous column, on the same line ... if it inserts otherwise it will delete
in this case the 20% would not be inserted because it is smaller
I tried to make the comparison in this way but it triggers this method every time I type and not when I lose focus
procedure TfrmConfiguraClassificacao.listaFaixasSetEditText(Sender: TObject;
ACol, ARow: Integer; const Value: string);
begin
if Acol=1 then
//check if it is larger
end;
You can validate the cell when the user moves to another cell (OnSelectCell) or when focus shifts to another control (OnExit).
Use the OnSetEditText event to store the last edited cell location.
Something along these lines:
Type
TfrmConfiguraClassificacao = Class(TForm)
...
private
fCol,fRow : Integer;
function CellValidated : Boolean;
...
end;
...
procedure TfrmConfiguraClassificacao.listaFaixasEnter(Sender : TObject);
begin // Initialize edited cell location
fCol := -1;
fRow := -1;
end;
procedure TfrmConfiguraClassificacao.listaFaixasSetEditText(Sender: TObject;
ACol, ARow: Integer; const Value: string);
begin // Save the edited cell location
fCol := ACol;
fRow := ARow;
end;
procedure TfrmConfiguraClassificacao.listaFaixasSelectCell(Sender : TObject;
ACol, ARow: Longint; var CanSelect: Boolean);
begin // Validate edited cell location
CanSelect := CellValidated;
end;
procedure TfrmConfiguraClassificacao.listaFaixasExit(Sender : TObject);
begin // Validate edited cell location
if not CellValidated then
// Handle focus redirection
end;
function TfrmConfiguraClassificacao.CellValidated : Boolean;
begin
Result := True;
if fCol=1 then begin
// if not larger, handle it and set Result to false
end;
end;
Related
I want to know on an overriding of DrawColumnCell if the grid is drawing its active row.
I thought of keeping an ActiveRecno private variable to check if the DrawColumnCell is drawing that row. I tried intercepting the DataChange of the Datasource to keep track of that ActiveRecno.
TMyDBGrid = class(TDBGrid)
protected
OnDataChange_Original: TDataChangeEvent;
procedure TrackPosition(Sender: TObject; Field: TField);
procedure DrawColumnCell(const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); override;
public
ActiveRecno: integer;
constructor Create(AOwner: TComponent): override;
...
...
implementation
constructor TMyDBGrid.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
OnDataChange_Original := nil;
if Assigned(DataSource) then begin
OnDataChange_Original := Datasource.OnDataChange;
Datasource.OnDataChange := TrackPosition;
end;
end;
procedure TMyDBGrid.TrackPosition(Sender: TObject; Field: TField);
begin
ActiveRecno := Datasource.DataSet.RecNo;
if Assigned(OnDataChange_Original) then OnDataChange_Original(Sender, Field);
end;
procedure TMyDBGrid.DrawColumnCell(const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
var ActiveRow: boolean;
begin
ActiveRow := (Self.ActiveRecno = Self.DataSource.Dataset.Recno);
...
...
inherited DrawColumnCell(Rect, DataCol, Column, State);
end;
But ActiveRecno remains always 0, making ActiveRow always False. That's because in the constructor Datasource is still nil, so I never set TrackPosition to keep the ActiveRecno.
Where can I set my handler for that event ?, the SetDataSource procedure is private, so I can't override it.
Do you recommend me another way to keep track of the active row, or detect in DrawColumnCell if the row to draw is the active row ?.
Thank you.
I think that what you want would be straightforward except for the fact that neither the current row
of the DBGrid nor the row being drawn in the OnDrawrDataCell event is readily accessible inside the event.
Fortunately, it is fairly straightforward to overcome these problems using an interposer TDBGrid class as shown below.
THe interposer TDBGrid class simply exposes the Row property of TCustomGrid as the ActiveRow
The OnDrawDataCell event is called from TCustomDBGrid.DrawCell, which is virtual and so can be overridden
in the interposer class. As you can see below, the overridden version first copies the row number (the ARow argument) used
in TCustomDBGrid.DrawCell into the FRowBeingDrawn field and then calls the inherited DrawDataCell, which in turn calls the OnDrawDataCell handler. Since this handler
sees the interposer class, both the grid's ActiveRow and RowBeingDrawn are accessible inside the
OnDrawDataCell event.
type
TDBGrid = class(DBGrids.TDBGrid)
private ,
FRowBeingDrawn : Integer;
function GetActiveRow: Integer;
protected
procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override;
property RowBeingDrawn : Integer read FRowBeingDrawn write FRowBeingDrawn;
property ActiveRow : Integer read GetActiveRow;
end;
TForm1 = class(TForm)
DBGrid1: TDBGrid;
ClientDataSet1: TClientDataSet;
DataSource1: TDataSource;
ComboBox1: TComboBox;
DBNavigator1: TDBNavigator;
procedure FormCreate(Sender: TObject);
procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
end;
[...]
procedure TForm1.FormCreate(Sender: TObject);
var
AField : TField;
begin
AField := TIntegerField.Create(Self);
AField.FieldKind := fkData;
AField.FieldName := 'ID';
AField.DataSet := ClientDataSet1;
AField := TStringField.Create(Self);
AField.FieldKind := fkData;
AField.FieldName := 'AValue';
AField.DataSet := ClientDataSet1;
ClientDataSet1.CreateDataSet;
ClientDataSet1.InsertRecord([1, 'One']);
ClientDataSet1.InsertRecord([2, 'Two']);
ClientDataSet1.InsertRecord([3, 'Three']);
ClientDataSet1.InsertRecord([4, 'Four']);
ClientDataSet1.InsertRecord([5, 'Five']);
DBGrid1.DefaultDrawing := True;
end;
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
if (Sender as TDBGrid).RowBeingDrawn = (Sender as TDBGrid).Row then
Caption := IntToStr((Sender as TDBGrid).RowBeingDrawn);
DBGrid1.DefaultDrawDataCell(Rect, Column.Field, State);
end;
procedure TDBGrid.DrawCell(ACol, ARow: Integer; ARect: TRect;
AState: TGridDrawState);
begin
RowBeingDrawn := ARow;
try
inherited;
finally
RowBeingDrawn := -1;
end;
end;
function TDBGrid.GetActiveRow: Integer;
begin
Result := Row;
end;
end.
The interposer class can, of course, be contained in a separate unit provided, of course, that it appears in the using unit's Uses list after DBGrids.
One minor point to beware of is that the code above does not take account of whether the title row of the grid is visble or not, and make require minor tweaking if it is not.
I'm building a function: after searching a value in DBGrid, it can count how many value and mark those cells (change cells' color).But I only made column change color.How can I do in one procedure?
procedure TfmMain.N_SearchClick(Sender: TObject);
var
searchname : String;
i: integer;
frmSearch : Tfrmsearch;
data_count : integer;
begin
searchData := '';
searchRow:=self.DBGrid.DataSource.DataSet.RecNo;
searchname:= DBGrid.DataSource.DataSet.fieldbyname('FIELD').AsString;
frmSearch:=Tfrmsearch.Create(self);
try
frmSearch.ShowModal;
frmSearch.Visible:=true;
for i := 0 to DBGrid.FieldCount do
begin
if ((Pos(searchData,DBGrid.DataSource.DataSet.Fields[i].AsString)>0) AND (CompareStr(searchData,'') <> 0)
AND (Pos('VALUE_',DBGrid.DataSource.DataSet.Fields[i].FieldName)>0)
AND (searchRow=DBGrid.DataSource.DataSet.RecNo)) then
begin
data_count:=data_count+1;
//DBGrid[DBGrid.Row,i-2].Color:=clLime;
end;
end;
showmessage('countTotal: '+IntToStr(data_count));
finally
frmSearch.Free;
end;
end;
All you need is something like this in the OnDrawColumnCell event of the grid:
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
// Change font- and grid-color if showing search results
if ShowingSearchResult then begin
TDBGrid(Sender).Canvas.Brush.Color := clSilver;
TDBGrid(Sender).Canvas.Font.Color := clBlue;
end;
TDBGrid(Sender).DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
What you can do in the OnDrawColumnCell event is a bit limited, but should suffice for this case. Iirc, at some point the OnDrawDataCell was added to allow for greater flexibility.
Of course, you would declare the ShowingSearchResult (boolean) variable as a field of your TfrmSearch and set it to True in your N_SearchClick procedure. However, since that procedure shows the form modally and then frees it, you can possibly omit that variable entirely, so the DBGrid1DrawColumnCell could be just
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
TDBGrid(Sender).Canvas.Brush.Color := clSilver;
TDBGrid(Sender).Canvas.Font.Color := clBlue;
TDBGrid(Sender).DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
Thanks a lot, this is final code that I wrote.
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
if (DBGrid.DataSource.DataSet.FieldByName(Column.FieldName).AsString = searchData)
and (searchRow=DBGrid.DataSource.DataSet.RecNo) then
begin
TDBGrid(Sender).Canvas.Brush.Color := $000080FF;
DBGrid.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
end;
i couldn't find the way to copy selected cell data from a stringgrid, i want the selected data string to be copied to Edit box if possible.. many thanks in advance.
im using delphi xe8, firemonkey.
what i tried so far..
Private
A : Array of TValue;
procedure TForm1.Grid1GetValue(Sender: TObject; const Col, Row: Integer; var Value: TValue);
begin
// Gets the value from a cell in the first column
if Col = 0 then
Value := A[Row];
procedure TForm1.Button2Click(Sender: TObject);
begin
A[1] := Edit1.Text;
end;
//i spent hours just to figure it out,waste of TIME;//
Procedure Formx.StringGrid1SellectCell(Sender: TObject; const ACol,Arow: integer; var CanSellect: Boolean);
Var
Val: string;
begin
Val := StringGrid1.Cells[ACol, ARow];
Edit1.Text:= Val;
I wrote such module to store there last changes of picture in my paint application " in Delphi
unit HistoryQueue;
interface
uses
Graphics;
type
myHistory = class
constructor Create(Size:Integer);
public
procedure Push(Bmp:TBitmap);
function Pop():TBitmap;
procedure Clean();
procedure Offset();
function isEmpty():boolean;
function isFull():boolean;
function getLast():TBitmap;
protected
historyQueueArray: array of TBitmap;
historyIndex, hSize:Integer;
end;
implementation
procedure myHistory.Push(Bmp:TBitmap);
var tbmp:TBitmap;
begin
if(not isFull) then begin
Inc(historyIndex);
historyQueueArray[historyIndex]:=TBitmap.Create;
historyQueueArray[historyIndex].Assign(bmp);
end else begin
Offset();
historyQueueArray[historyIndex]:=TBitmap.Create;
historyQueueArray[historyIndex].Assign(bmp);
end;
end;
procedure myHistory.Clean;
var i:Integer;
begin
{ for i:=0 to hSize do begin
historyQueueArray[i].Free;
historyQueueArray[i].Destroy;
end; }
end;
constructor myHistory.Create(Size:Integer);
begin
hSize:=Size;
SetLength(historyQueueArray, hSize);
historyIndex:=-1;
end;
function myHistory.isEmpty: boolean;
begin
Result:=(historyIndex = -1);
end;
function myHistory.isFull: boolean;
begin
Result:=(historyIndex = hSize);
end;
procedure myHistory.Offset; {to handle overflow}
var i:integer;
begin
//historyQueueArray[0]:=nil;
for i:=0 to hSize-1 do begin
historyQueueArray[i]:=TBitmap.Create;
historyQueueArray[i].Assign(historyQueueArray[i+1]);
end;
end;
function myHistory.Pop: TBitmap;
var
popBmp:TBitmap;
begin
popBmp:= TBitmap.Create;
popBmp.Assign(historyQueueArray[historyIndex]);
Dec(historyIndex);
Result:=popBmp;
end;
function myHistory.getLast: TBitmap; {this function I use when I need refresh the cnvas when I draw ellipse or rect, to get rid of traces and safe previous changes of the picture}
var
tBmp:TBitmap;
begin
tBmp:= TBitmap.Create;
tBmp.Assign(historyQueueArray[historyIndex]);
Result:=tBmp;
end;
end.
And thats how I use it
procedure TMainForm.FormCreate(Sender: TObject);
var
cleanBmp:TBitmap;
begin
{...}
doneRedo:=false;
redomode:=false; undomode:=false;
//init arrays
picHistory:=myHistory.Create(10); //FOR UNDO
tempHistory:=myHistory.Create(10); //FOR REDO
cleanbmp:=TBitmap.Create;
cleanbmp.Assign(imgMain.Picture.Bitmap);
picHistory.Push(cleanbmp);
cleanbmp.Free;
{...}
end;
procedure TMainForm.btnUndoClick(Sender: TObject);
var redBmp:TBitmap;
begin
undoMode:=true;
//if there were some changes
if(not picHistory.isEmpty) then begin
redBmp:=TBitmap.Create;
redBmp.Assign(picHistory.getLast);
//clean canvas
imgMain.Picture.Bitmap:=nil;
//get what was there before
imgMain.Canvas.Draw(0,0, picHistory.Pop);
//and in case if we will not make any changes after UNDO(clicked one or more times)
//and call REDO then
tempHistory.Push(redBmp);//we save what were on canvas before UNDOand push it to redo history
redBmp.Free;
end;
end;
procedure TMainForm.btnRedoClick(Sender: TObject);
var undBmp:TBitmap;
begin
redoMode:=true;
if(not tempHistory.isEmpty) then begin
doneRedo:=True;
undBmp:=TBitmap.Create;
undBmp.Assign(tempHistory.getLast);
imgMain.Picture.Bitmap:=nil;
MainForm.imgMain.Canvas.Draw(0,0, tempHistory.Pop);
//same history (like with UNDO implementation) here but reverse
picHistory.Push(undBmp);
undBmp.Free;
end;
end;
{...}
procedure TMainForm.imgMainMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var bmp:TBitmap;
begin
//if mouse were down and then it's up this means we drew something
//and must save changes into history to be able to make UNDO
{...}
bmp:=TBitmap.Create;
try
bmp.Assign(imgMain.Picture.Bitmap);
picHistory.Push(bmp);
//if there are some changes added after redo then we clean redo history
if (doneRedo) then begin
tempHistory.Clean;
doneRedo:=false;
end;
finally
bmp.Free;
//sor of refresh
imgMain.Canvas.Draw(0,0, picHistory.getLast);
end;
{...}
But the problem is it works not way I expected. an example:
If I push undo button once - nothing happens. On twice - it does what it should at once.
And if I drew an ellipse, then click undo once and start draw new one - last drawn ellipse just dissaperas!
Here's the elipse draw method in case if it could be helpful to find out the problem
procedure TMainForm.ellipseDraw(X, Y: Integer);
begin
imgMain.Canvas.Pen.Color:=useColor;
imgMain.Canvas.Brush.Color:=scndColor;
imgMain.Canvas.Pen.Width:=size;
if(mouseIsDown) then begin
imgMain.Canvas.Draw(0,0, picHistory.getLast); //there gonna be no bizzare traces from figures
imgMain.Canvas.Ellipse(dX, dY, X,Y);
end;
end;
Answer
If I push undo button once - nothing happens. On twice - it does what it should at once.
That is indeed exactly what your code does:
In imgMainMouseUp you add the current picture to the undo list, and
In btnUndoClick you retrieve the last bitmap from the undo list, which is the same as currently seen on the Image.
The solution - to this specific question - is to add the previous bitmap to the undo list instead of the current one.
Bonus
And to address David's comment concerning the leaking, your implementation leaks Bitmaps because:
The routines Pop and getLast return a newly local created Bitmap. This places the responsibility for its destruction on the caller ot the routines. Your MainForm code does not destroy those Bitmaps, thus they are memory leaks. The solution is to simply return the item in the array, instead of creating a new Bitmap.
In the Offset routine, you again create new Bitmaps and leak all previous ones. Just assign Queue[I] to Queue[I + 1].
In the Push method, you forget to free the last item.
The class does not have a destructor, which again places the responsibility for the destruction of all Bitmaps on the user of the object with the need to call Clean, which it does not. The solution is to add a destructor to your object which calls Clean.
Besides these leaks, there are more problems with your code. Here some fixes and tips:
Since dynamic arrays are zero-based, your isFull routine does not return True when it should. It should be implemented as Result := historyIndex = hSize - 1;
Your array is not a queue (FIFO), but a stack (LIFO).
Your Pop routine does not check for an empty list.
Altogether, your history class could better look like:
uses
SysUtils, Graphics;
type
TBitmapHistory = class(TObject)
private
FIndex: Integer;
FStack: array of TBitmap;
procedure Offset;
public
procedure Clear;
function Count: Integer;
constructor Create(ACount: Integer);
destructor Destroy; override;
function Empty: Boolean;
function Full: Boolean;
function Last: TBitmap;
function Pop: TBitmap;
procedure Push(ABitmap: TBitmap);
end;
implementation
{ TBitmapHistory }
procedure TBitmapHistory.Clear;
var
I: Integer;
begin
for I := 0 to Count - 1 do
FreeAndNil(FStack[I]);
FIndex := -1;
end;
function TBitmapHistory.Count: Integer;
begin
Result := Length(FStack);
end;
constructor TBitmapHistory.Create(ACount: Integer);
begin
inherited Create;
SetLength(FStack, ACount);
FIndex := -1;
end;
destructor TBitmapHistory.Destroy;
begin
Clear;
inherited Destroy;
end;
function TBitmapHistory.Empty: Boolean;
begin
Result := FIndex = -1;
end;
function TBitmapHistory.Full: Boolean;
begin
Result := FIndex = Count - 1;
end;
function TBitmapHistory.Last: TBitmap;
begin
if Empty then
Result := nil
else
Result := FStack[FIndex];
end;
procedure TBitmapHistory.Offset;
begin
FStack[0].Free;
Move(FStack[1], FStack[0], (Count - 1) * SizeOf(TBitmap));
end;
function TBitmapHistory.Pop: TBitmap;
begin
if not Empty then
begin
Result := Last;
Dec(FIndex);
end;
end;
procedure TBitmapHistory.Push(ABitmap: TBitmap);
begin
if Full then
Offset
else
Inc(FIndex);
FStack[Findex].Free;
FStack[FIndex] := TBitmap.Create;
FStack[Findex].Assign(ABitmap);
end;
Remarks:
There also exists a specialized class TObjectStack for this in the Contnrs unit which you could override/exploit.
There are also concerns with your MainForm code, but I politely leave that up to you to fix.
It seems something obvious to have. I want the texts to be in the center of the cells, but for some reason I can't find it in properties. How can I do this?
There's no property to center the text in TStringGrid, but you can do that at DrawCell event as:
procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
S: string;
SavedAlign: word;
begin
if ACol = 1 then begin // ACol is zero based
S := StringGrid1.Cells[ACol, ARow]; // cell contents
SavedAlign := SetTextAlign(StringGrid1.Canvas.Handle, TA_CENTER);
StringGrid1.Canvas.TextRect(Rect,
Rect.Left + (Rect.Right - Rect.Left) div 2, Rect.Top + 2, S);
SetTextAlign(StringGrid1.Canvas.Handle, SavedAlign);
end;
end;
The code I posted from here
UPDATE:
to center text while writing in the cell, add this code to GetEditText Event:
procedure TForm1.StringGrid1GetEditText(Sender: TObject; ACol, ARow: Integer;
var Value: string);
var
S : String;
I: Integer;
IE : TInplaceEdit ;
begin
for I := 0 to StringGrid1.ControlCount - 1 do
if StringGrid1.Controls[i].ClassName = 'TInplaceEdit' then
begin
IE := TInplaceEdit(StringGrid1.Controls[i]);
ie.Alignment := taCenter
end;
end;
This one is a much better solution that the others and on them there was a mistype on procedures TStringGrid.SetCellsAlignment and TStringGrid.SetCellsAlignment the (-1 < Index) compare was correct, but then and else parts were swapped... The correct version (this one) will show that when index is bigger than -1 it will overwrite value stored else it will add a new entry, the others will do just the oposite bringing a list out of index message, thanks for detecting such.
I have also make able to be all in another separated unit, so here it is (hope now it is correct and thanks for detecting such mistypes):
unit AlignedTStringGrid;
interface
uses Windows,SysUtils,Classes,Grids;
type
TStringGrid=class(Grids.TStringGrid)
private
FCellsAlignment:TStringList;
FColsDefaultAlignment:TStringList;
function GetCellsAlignment(ACol,ARow:Integer):TAlignment;
procedure SetCellsAlignment(ACol,ARow:Integer;const Alignment:TAlignment);
function GetColsDefaultAlignment(ACol:Integer):TAlignment;
procedure SetColsDefaultAlignment(ACol:Integer;const Alignment:TAlignment);
protected
procedure DrawCell(ACol,ARow:Longint;ARect:TRect;AState:TGridDrawState);override;
public
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
property CellsAlignment[ACol,ARow:Integer]:TAlignment read GetCellsAlignment write SetCellsAlignment;
property ColsDefaultAlignment[ACol:Integer]:TAlignment read GetColsDefaultAlignment write SetColsDefaultAlignment;
end;
implementation
constructor TStringGrid.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
FCellsAlignment:=TStringList.Create;
FCellsAlignment.CaseSensitive:=True;
FCellsAlignment.Sorted:=True;
FCellsAlignment.Duplicates:=dupIgnore;
FColsDefaultAlignment:=TStringList.Create;
FColsDefaultAlignment.CaseSensitive:=True;
FColsDefaultAlignment.Sorted:=True;
FColsDefaultAlignment.Duplicates:=dupIgnore;
end;
destructor TStringGrid.Destroy;
begin
FCellsAlignment.Free;
FColsDefaultAlignment.Free;
inherited Destroy;
end;
procedure TStringGrid.SetCellsAlignment(ACol,ARow: Integer; const Alignment: TAlignment);
var
Index:Integer;
begin
if (-1 < Index) then begin
FCellsAlignment.Objects[Index]:= TObject(Alignment);
end else begin
FCellsAlignment.AddObject(IntToStr(ACol) + '-' + IntToStr(ARow), TObject(Alignment));
end;
end;
function TStringGrid.GetCellsAlignment(ACol,ARow: Integer): TAlignment;
var
Index:Integer;
begin
Index:= FCellsAlignment.IndexOf(IntToStr(ACol)+'-'+IntToStr(ARow));
if (-1 < Index) then begin
GetCellsAlignment:= TAlignment(FCellsAlignment.Objects[Index]);
end else begin
GetCellsAlignment:= ColsDefaultAlignment[ACol];
end;
end;
procedure TStringGrid.SetColsDefaultAlignment(ACol: Integer; const Alignment: TAlignment);
var
Index:Integer;
begin
Index:= FColsDefaultAlignment.IndexOf(IntToStr(ACol));
if (-1 < Index) then begin
FColsDefaultAlignment.Objects[Index]:= TObject(Alignment);
end else begin
FColsDefaultAlignment.AddObject(IntToStr(ACol), TObject(Alignment));
end;
end;
function TStringGrid.GetColsDefaultAlignment(ACol:Integer):TAlignment;
var
Index:Integer;
begin
Index:= FColsDefaultAlignment.IndexOf(IntToStr(ACol));
if (-1 < Index) then begin
GetColsDefaultAlignment:= TAlignment(FColsDefaultAlignment.Objects[Index]);
end else begin
GetColsDefaultAlignment:=taLeftJustify;
end;
end;
procedure TStringGrid.DrawCell(ACol,ARow:Longint;ARect:TRect;AState:TGridDrawState);
var
Old_DefaultDrawing:Boolean;
begin
if DefaultDrawing then begin
case CellsAlignment[ACol,ARow] of
taLeftJustify: begin
Canvas.TextRect(ARect,ARect.Left+2,ARect.Top+2,Cells[ACol,ARow]);
end;
taRightJustify: begin
Canvas.TextRect(ARect,ARect.Right -2 -Canvas.TextWidth(Cells[ACol,ARow]), ARect.Top+2,Cells[ACol,ARow]);
end;
taCenter: begin
Canvas.TextRect(ARect,(ARect.Left+ARect.Right-Canvas.TextWidth(Cells[ACol,ARow]))div 2,ARect.Top+2,Cells[ACol,ARow]);
end;
end;
end;
Old_DefaultDrawing:= DefaultDrawing;
DefaultDrawing:=False;
inherited DrawCell(ACol,ARow,ARect,AState);
DefaultDrawing:= Old_DefaultDrawing;
end;
end.
This is a whole unit, save it to a file called AlignedTStringGrid.pas.
Then on any form you have a TStringGrid add ,AlignedTStringGrid at the end of the interface uses clause.
Note: The same can be done for rows, but for now I do not know how to mix both (cols and rows) because of how to select priority, if anyone is very interested on it let me know.
P.D.: The same idea is possible to be done for TEdit, just search on stackoverflow.com for TEdit.CreateParams or read post How to set textalignment in TEdit control