2012-08-01

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

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

在 DBGrid 的 OnMouseMove 寫入

 
procedure TForm1.DBGrid1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
    pt: TGridcoord;
begin
    // 判別滑鼠是否移動到標題列
    // 若是, 則滑鼠為手指形,
    // 否則為預設
    pt := DBGrid1.MouseCoord(x, y);

    if pt.y=0 then
        DBGrid1.Cursor:=crHandPoint
    else
        DBGrid1.Cursor:=crDefault;
end;
 

再在 OnTitleClick 寫入
 
procedure TForm1.DBGrid1TitleClick(Column: TColumn);
{$J+}
// 指定為靜態變數
// 做為記錄前次滑鼠點擊的欄位
const PreviousColumnIndex : integer = 0;
{$J-}
begin
    if DBGrid1.DataSource.DataSet is TCustomADODataSet then
        with TCustomADODataSet(DBGrid1.DataSource.DataSet) do
        begin
            try
                DBGrid1.Columns[PreviousColumnIndex].title.Font.Style := DBGrid1.Columns[PreviousColumnIndex].title.Font.Style - [fsBold];
            except

            end;

            Column.title.Font.Style := Column.title.Font.Style + [fsBold];
            DBGrid1.Columns[PreviousColumnIndex].Title.Caption := StringReplace(DBGrid1.Columns[PreviousColumnIndex].Title.Caption,' ▲', '',[rfReplaceAll]);
            DBGrid1.Columns[PreviousColumnIndex].Title.Caption := StringReplace(DBGrid1.Columns[PreviousColumnIndex].Title.Caption,' ▼', '',[rfReplaceAll]);
            PreviousColumnIndex := Column.Index;

            if (Pos(Column.Field.FieldName, Sort)=1) and (Pos(' DESC',Sort)=0) then
                begin
                    Sort := Column.Field.FieldName + ' DESC';
                    DBGrid1.Columns[PreviousColumnIndex].Title.Caption := DBGrid1.Columns[PreviousColumnIndex].Title.Caption + ' ▼';
                end
            else
                begin
                    Sort := Column.Field.FieldName + ' ASC';
                    DBGrid1.Columns[PreviousColumnIndex].Title.Caption := DBGrid1.Columns[PreviousColumnIndex].Title.Caption + ' ▲';
                end;
        end;
end;
 

自己再自行做變化.

沒有留言:

張貼留言