2012-08-01

【Delphi】以滑鼠點擊 DBGrid 欄位標題做資料排序

開一個新專案, 在 Form1 上放一個 TADOConnect, TADOTable(或 TADOQuery), TDataSource, TDBGrid, 設定好要連接的資料庫, Table 名稱.

在 DBGrid 的 OnMouseMove 寫入

  1.  
  2. procedure TForm1.DBGrid1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
  3. var
  4. pt: TGridcoord;
  5. begin
  6. // 判別滑鼠是否移動到標題列
  7. // 若是, 則滑鼠為手指形,
  8. // 否則為預設
  9. pt := DBGrid1.MouseCoord(x, y);
  10.  
  11. if pt.y=0 then
  12. DBGrid1.Cursor:=crHandPoint
  13. else
  14. DBGrid1.Cursor:=crDefault;
  15. end;
  16.  

再在 OnTitleClick 寫入
  1.  
  2. procedure TForm1.DBGrid1TitleClick(Column: TColumn);
  3. {$J+}
  4. // 指定為靜態變數
  5. // 做為記錄前次滑鼠點擊的欄位
  6. const PreviousColumnIndex : integer = 0;
  7. {$J-}
  8. begin
  9. if DBGrid1.DataSource.DataSet is TCustomADODataSet then
  10. with TCustomADODataSet(DBGrid1.DataSource.DataSet) do
  11. begin
  12. try
  13. DBGrid1.Columns[PreviousColumnIndex].title.Font.Style := DBGrid1.Columns[PreviousColumnIndex].title.Font.Style - [fsBold];
  14. except
  15.  
  16. end;
  17.  
  18. Column.title.Font.Style := Column.title.Font.Style + [fsBold];
  19. DBGrid1.Columns[PreviousColumnIndex].Title.Caption := StringReplace(DBGrid1.Columns[PreviousColumnIndex].Title.Caption,' ▲', '',[rfReplaceAll]);
  20. DBGrid1.Columns[PreviousColumnIndex].Title.Caption := StringReplace(DBGrid1.Columns[PreviousColumnIndex].Title.Caption,' ▼', '',[rfReplaceAll]);
  21. PreviousColumnIndex := Column.Index;
  22.  
  23. if (Pos(Column.Field.FieldName, Sort)=1) and (Pos(' DESC',Sort)=0) then
  24. begin
  25. Sort := Column.Field.FieldName + ' DESC';
  26. DBGrid1.Columns[PreviousColumnIndex].Title.Caption := DBGrid1.Columns[PreviousColumnIndex].Title.Caption + ' ▼';
  27. end
  28. else
  29. begin
  30. Sort := Column.Field.FieldName + ' ASC';
  31. DBGrid1.Columns[PreviousColumnIndex].Title.Caption := DBGrid1.Columns[PreviousColumnIndex].Title.Caption + ' ▲';
  32. end;
  33. end;
  34. end;
  35.  

自己再自行做變化.

沒有留言:

張貼留言