透過DBGrid的OnDrawColumnCell事件將字體變色

透過DBGrid的OnDrawColumnCell事件將字體變色

由大衛王(david king) 發表於 [ Delphi ]
(1666) 閱讀(0) 引用(0) 回應 , 推文( 2 )

有時候我們常會需要將DBGrid中某Cell依照某條件下將字體變色,以突顯其重要。如果要做到這點,就得尋找DB顯示文字前所觸發的事件。Search一下後,確認DBGrid有兩個關於資料的顯示時會觸發的事件,分別是OnDrawColumnCell以及OnDrawDataCell。OnDrawDataCell在Delphi 6中僅是了為了相容而存在的,Delphi建議用OnDrawColumnCell取代它。因此我們只要關注OnDataColumnCell即可。

假設我們需要判斷TQuery中cfm_code欄位值如果為Y就將字體變成藍色,否則就維持預設的字體顏色。

procedure TMasterFM.DBGrid2DrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn;
  State: TGridDrawState);
begin
inherited;
  //有效的藍色字體, 否則就是黑色
if (myQuery1.FieldByName('cfm_code').AsString = 'Y') then
      DBGrid1.Canvas.Font.Color := clBlue;
  DBGrid1.DefaultDrawDataCell(Rect,Column.Field,State);
end;

程式中我們利用了DBGGrid中的Canvas物件,取出其字體屬性後變更其顏色。最後利用DefaultDrawDataCell方法將欄位值繪入DBGrid的指定Cell。另請注意,DBGrid.DefaultDrawing的屬性與OnDrawColumnCell事件行為也息息相關。

DefaultDrawing預設為True,表示如果沒有於自訂OnDrawColumnCell事件中呼叫行DefaultDrawDataCell方法,則以Canvas預設設定自動呼叫DefaultDrawDataCell。如果設定為False,表示如果沒有於自訂OnDrawColumnCell事件中呼叫行DefaultDrawDataCell方法,則不自動將欄位值填入Cell中,因此欄位會是空白的。這點在開發時倒是要小心一點。

03 六月, 2009 09:45

啟用DBGrid中Field的Lookup功能

由大衛王(david king) 發表於 [ Delphi ]
(1660) 閱讀(0) 引用(0) 回應 , 推文( 0 )

Delphi中有個大家都不陌生的Lookup功能,只要將Field中的LookupDataSet、KeyFields、LookupKeyFields、以及LookupResultField設定完就搞定。那 ,接下來我們在DBGrid中試著測試LookUp的結果,卻發現以下狀況:

  • 新增狀態下,輸入Key Field的欄位值並按下tab鍵後,指定的ResultFiled並沒有出現預期的Lookup結果
  • 把游標移往下一行後,Lookup的機制才被啟動,進而將LookupResultField結果顯示出來

研究了半天才發現,原來DataSet有個關鍵卻很謙虛的AutoCalcFields屬性值必須設定為True,預期的Lookup效果才會正確的出現。查了Help後,Delphi對該欄位如此解釋:

When AutoCalcFields is True (the default), Lookup fields are recalculated and OnCalcFields is triggered when:

  • The dataset is opened.
  • The dataset is put into dsEdit state.
  • Focus moves from one visual control to another, or from one column to another in a data-aware grid and modifications have been made to the record.

When AutoCalcFields is False, Lookup fields are recalculated and the OnCalcFields event occurs only when

  • The dataset is opened.
  • The dataset is put into dsEdit state.
  • A record is retrieved from a database.

看來,還得根據不同的UI行為設定下才能正確的得到預期的結果。

關於Delphi常有這種大隱隱於市的屬性設定來說,在開發過程中的確有不小的困擾。更別提現在還是在Delphi6的環境下開發,比起現有的RAD工具說明,其Help組織就遜色不少。這時,我就莫名的感謝MS了。

 

 

free counters
Free counters

posted on 2011-12-16 10:50  舟山牙医  阅读(2151)  评论(0编辑  收藏  举报

导航