Reputation: 83
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;
Upvotes: 1
Views: 1328
Reputation: 83
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;
Upvotes: 0
Reputation: 30715
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;
Upvotes: 2