2013-05-28 46 views

回答

14

您可以輕鬆地實現這個使用DBGrids onDrawColumnCell事件:

procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; 
    DataCol: Integer; Column: TColumn; State: TGridDrawState); 
begin 
if Table1.FieldByName('Teacher').AsString = 'Joe' 
then 
    DBGrid1.Canvas.Brush.Color:=clRed; 
DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); 

end; 

但是,如果你不知道教師的名字,那麼你將不得不實施某種遞歸的行動,這是我實現:

var TeacherStringList : TStringList; 
    lastColorUsed : TColor; 
    AColors : Array of TColor; 


function mycolor: TColor; 
begin 
    result := RGB(Random(256), Random(256), Random(256)); 
end; 

procedure TForm3.Button1Click(Sender: TObject); 
var CurrS : String; 
    Index : Integer; 
begin 

    if TeacherStringList.Count <> 0 then TeacherStringList.Clear; 
    Table1.DisableControls; 
    try 
    while not Table1.Eof do 
    begin 

     CurrS := Table1.FieldByName('Teacher').AsString; 
     if (not TeacherStringList.Find(CurrS,Index)) and (not currS.IsEmpty) 
     then TeacherStringList.Add(CurrS); 
     Table1.Next; 

    end; 
    Table1.First; 
    SetLength(AColors,TeacherStringList.Count); 
    for Index := Low(AColors) to High(AColors) 
    do AColors[Index] := mycolor; 

    finally 
    Table1.EnableControls; 
    end; 

end; 

procedure TForm3.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; 
    DataCol: Integer; Column: TColumn; State: TGridDrawState); 
var Index : integer; 

begin 

    if (TeacherStringList.Find(Table1.FieldByName('Teacher').AsString,Index)) 
    then 
    DBGrid1.Canvas.Brush.Color:= AColors[index]; 

    DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State); 

end; 

procedure TForm3.FormCreate(Sender: TObject); 
begin 
    teacherStringList := TStringList.Create; 
    teacherStringList.Sorted := True; 
end; 

procedure TForm3.FormDestroy(Sender: TObject); 
begin 
    teacherStringList.Free; 
end; 
+0

這是不行的,因爲我不知道老師的名字 – teocka

+0

假設:Table1.FieldByName(「老師」)AsString的前10行=「喬」; Table1.FieldByName('Teacher')。AsString ='Jack'in next 5 rows; Table1.FieldByName('Teacher')。AsString ='Jim'in next 8 rows;我需要前10行是灰色的,接下來的5行是白色的,接下來的8行是灰色的,接下來是白色的 – teocka

+1

請注意,在下面的問題中,請儘可能提供儘可能多的數據,更新我的答案。 – Peter