Delphi TJvStringGridでセルを並び替え|JEDIコンポーネントでグリッドソートを実装する方法
DelphiのTJvStringGridを使ってセルの並び替え(ソート)を実装する方法を解説。
JEDI Visual Component Library(JVCL)を導入し、クリック操作で昇順・降順に並び替える処理をサンプルコード付きで紹介。
TStringGridとの違いやCommaTextの活用も補足。
Delphi10.4 Community Editionの場合は[GetItパッケージマネージャー]から
「JCL(JEDI Component Library)」と「JVCL(JEDI Visual Component Library)」をインストールすると
「TJvStringGrid」を使うことが出来ます。
インストール後はDelphiの再起動が必要みたいです。
TJvStringGridはTStringGridから派生したクラスで、標準でカラムのソート(並び替え)機能があるので便利です。
フォーム画面の作成
Delphi IDEを起動し、「ファイル」⇒「Windows VCLアプリケーション -Delphi」をクリックします
フォームにTJvStringGridをドラッグ&ドロップします。
プログラムの作成
以下ソースコードを記述します。
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, JvExGrids, JvStringGrid;
type
TForm1 = class(TForm)
JvStringGrid1: TJvStringGrid;
procedure FormCreate(Sender: TObject);
procedure JvStringGrid1FixedCellClick(Sender: TObject; ACol, ARow: Integer);
private
{ Private 宣言 }
public
{ Public 宣言 }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var i:integer;
begin
//フォントサイズの設定
JvStringGrid1.font.Size:=10;
JvStringGrid1.FixedFont.size:=10;
JvStringGrid1.FixedFont.Style:=
JvStringGrid1.FixedFont.Style+[fsBold];
JvStringGrid1.FixedCols:=0;
JvStringGrid1.FixedRows:=1;
JVStringGrid1.ColCount:=2;
JvStringGrid1.RowCount:=11;
//固定行をクリック可能に設定する
JvStringGrid1.Options:=
JvStringGrid1.Options + [goFixedRowClick];
//列タイトルの設定
JvStringGrid1.Rows[0].CommaText:='連番,乱数';
Randomize;
for i := 1 to 10 do
begin
JvStringGrid1.Cells[0,i]:=Format('%2.2d',[i]);
JvStringGrid1.Cells[1,i]:=Format('%2.2d',[random(100)]);
end;
JvStringGrid1FixedCellClick(nil,0,0);
end;
procedure TForm1.JvStringGrid1FixedCellClick(Sender: TObject; ACol,
ARow: Integer);
var st:string;
order:Boolean;
i:Integer;
begin
st:=JvStringGrid1.Cells[ACol,0];
if st.Substring(0,1)='▼' then
begin
order:=False;
st:='▲'+st.Substring(1,length(st)-1);
end
else if st.Substring(0,1)='▲' then
begin
order:=True;
st:='▼'+st.Substring(1,length(st)-1);
end
else
begin
order:=True;
st:='▼'+st;
end;
for i := 0 to JvStringGrid1.ColCount-1 do
begin
JvStringGrid1.Cells[i,0]:=
StringReplace(JvStringGrid1.Cells[i,0],'▼','',[rfReplaceAll]);
JvStringGrid1.Cells[i,0]:=
StringReplace(JvStringGrid1.Cells[i,0],'▲','',[rfReplaceAll]);
end;
JvStringGrid1.Cells[ACol,0]:=st;
//固定行をクリックした時に並び変える
JvStringGrid1.SortGrid(
ACol, //並び替え基準列番号指定
order, //True:昇順 false:降順
True, //固定行は並び替えしない
stAutomatic,//並び替えタイプ
true //True:空のセルを上に移動させる
);
end;
end.
実行する
列タイトル「連番」「乱数」をクリックすると、昇順・降順にソート(並び替え)されます。
