luni, 21 septembrie 2015

Lazarus / FPC: sort a StringGrid

Here it is, a nice simple procedure that sorts a StringGrid. Tested an a 5000 records StringGrid, the sorting is done in about 1-2 seconds
   sg: your stringgrid
   col: column that will be sorted
   numeric: if the values in column are numbers
   asc: ascendent or descendent
   numeric: if datas are numbers

procedure sort(sg:tstringgrid;col:integer;asc:boolean=true;numeric:boolean);
var i,c:integer; numeric:boolean; f:string; r:real; negat:boolean; x1:integer; semn,s1,s2:string;
begin
  numeric:=false;
  negat:=false;


  if asc=true then sg.SortOrder:=soascending else sg.SortOrder:=sodescending;

  if numeric=false then
     sg.SortColRow(true, col, sg.FixedRows, sg.RowCount-1)
  else begin
     f:='000000000000000.00';
     c:=sg.colcount;
     sg.ColCount:=c+1;
     for i:=1 to sg.RowCount-1 do
       begin
          try r:=strtofloat(sg.Cells[col,i]) except r:=0 end;
          if r<0 then
            begin
              negat:=true;
              sg.Cells[c,i]:='-'+formatfloat(f,r);
            end else sg.Cells[c,i]:='+'+formatfloat(f,r);
       end;
     sg.SortColRow(true, c, sg.FixedRows, sg.RowCount-1);
     if negat=true then
       begin
          x1:=0;
          semn:=sg.Cells[c,0][1];
          s1:=semn; s2:=' ';
          for i:=0 to sg.RowCount-1 do
            if sg.Cells[c,0][1]<>semn then
              begin
                semn:=sg.Cells[c,0][1];
                s2:=semn;
                x1:=i;
              end;
          if s1='-' then
            begin
               if sg.SortOrder=soascending then sg.SortOrder:=sodescending else sg.SortOrder:=soascending;
               sg.SortColRow(true, c, sg.FixedRows, x1-1);
            end;
          if s2='-' then
            begin
               if sg.SortOrder=soascending then sg.SortOrder:=sodescending else sg.SortOrder:=soascending;
               sg.SortColRow(true, c, x1, sg.RowCount-1);
            end;
       end;
     sg.ColCount:=c;
  end;
end;

Niciun comentariu:

Trimiteți un comentariu