在 DBGrid1 的 OnDrawColumnCell 事件中,依據記錄號奇偶決定背景色,並自行繪製文字。
void __fastcall TForm1::DBGrid1DrawColumnCell(TObject *Sender,
const TRect &Rect, int DataCol, TColumn *Column, TGridDrawState State)
{
if (Column->Field->DataSet->RecNo % 2) { // 奇數行
DBGrid1->Canvas->Brush->Color = clSkyBlue;
DBGrid1->Canvas->FillRect(Rect);
}
// 置中繪製文字
DrawText(DBGrid1->Canvas->Handle,
Column->Field->Text.c_str(), -1,
(RECT*)&Rect,
DT_SINGLELINE | DT_VCENTER | DT_CENTER);
}
注意:必須自行繪製文字 (DrawText),否則預設繪製會覆蓋背景。
void __fastcall TForm1::Button1Click(TObject *Sender)
{
for (int i = 0; i < DBGrid1->Columns->Count; i++) {
if (i % 2 == 0) DBGrid1->Columns->Items[i]->Color = clAqua;
else DBGrid1->Columns->Items[i]->Color = clInfoBk;
}
}
此法直接設定 TColumn::Color 屬性,效果永久且無需自繪事件,適合固定欄位著色需求。
OnDrawColumnCell 中使用 Canvas 完整自繪。DataSet->RecNo 或自訂欄位值判斷。