자유롭게 질의 및 응답을 할 수 있는 게시판입니다. 개발자 여러분의 답변이 큰 도움이 됩니다. 
  • 제품설치/등록 오류 문의: 설치/등록 Q&A 이용 (제품 구매 고객 한정)

Q, 

스트링그리드를 정렬하고 싶습니다.


A.

다음 소스코드를 참고하시기 바랍니다.

GridSortSource.zip 

스트링그리드 컬럼을 선택하면 해당 컬럼으로 정렬됩니다.


{ ************** SortGrid ************* }

procedure TForm1.SortGrid(Grid: TStringGrid; SortCol: Integer);

{ A simple exchange sort of grid rows }

var

  I, J: Integer;

  temp: TStringList;

begin

  temp := TStringList.create;

  with Grid do

    for I := FixedRows to RowCount - 2 do { because last row has no next row }

      for J := I + 1 to RowCount - 1 do { from next row to end }

        if AnsiCompareText(Cells[SortCol, I], Cells[SortCol, J]) > 0 then

        begin

          temp.assign(Rows[J]);

          Rows[J].assign(Rows[I]);

          Rows[I].assign(temp);

        end;

  temp.free;

end;


procedure TForm1.FormCreate(Sender: TObject);

var

  I, J: Integer;

  totwidth: Integer;

begin

  with StringGrid1 do

  begin

    { assign some random numbers }

    for J := 1 to RowCount - 1 do

      for I := 1 to colcount - 1 do

        Cells[I, J] := Format('%3d', [Random(1000)]);


    { Add row labels }

    for I := 1 to RowCount - 1 do

      Cells[0, I] := 'Row ' + Format('%2d', [I]);


    { Add column labels and change column widths }

    totwidth := 0;

    for I := 0 to colcount - 1 do

    begin

      Cells[I, 0] := 'Column ' + IntToStr(I + 1);

      { vary column widths for testing }

      Colwidths[I] := DefaultColWidth + Random(48);

      Inc(totwidth, Colwidths[I]);

    end;

    { adjust grid width so that all column are visible }

    Width := totwidth + (colcount + 3) * GridLineWidth;

  end;

end;


{ ************ StringgridMouseUp ************** }

procedure TForm1.StringGrid1MouseUp(Sender: TObject; Button: TMouseButton;

  Shift: TShiftState; X, Y: Integer);

var

  c, J: Integer;

  rect: TRect;

begin

  with StringGrid1 do

    if Y < RowHeights[0] then { make sure row 0 was clicked }

    begin

      for J := 0 to colcount - 1 do { determine which column was clicked }

      begin

        rect := CellRect(J, 0);

        if (rect.Left < X) and (rect.Right > X) then

        begin

          c := J;

          break;

        end;

      end;

      SortGrid(StringGrid1, c);

    end;

end;

=============

string grid sort.txt 

string grid sort2.txt

번호 제목 글쓴이 날짜 조회 수
공지 [프로그래밍 강의] 2021.6~2021.12 관리자 2015.01.22 39921
공지 유용한 관련 사이트 관리자2 2014.03.20 79450
269 그리드에서 엑셀과 비슷한 기능으로 필터링을 구현하고 싶은데요. [1] jksun 2014.08.08 2307
268 폼과 에디터 창 전환시 응답없음이 뜹니다. [2] file 가람아빠 2014.04.22 2310
267 구글 플레이스토어에 올릴 때 업로드 실패. [2] file ScorpioM 2014.05.02 2313
266 IdTcpServer와 IdTcpClient를 이용한 Sample 예제 있나요? [2] 거북선생 2016.10.26 2314
265 Treeview, DBGrid Flicking 동작 nops 2014.05.27 2330
264 sqlite DB에 POST하면 에러(database is locked)가 발생합니다. [2] 스카이 2018.06.14 2355
263 한글깨짐문제 [안드로이드, 아이폰 [6] silkroad99 2015.06.25 2356
262 [공유] 웹뷰를 이용한 하이브리드 앱 개발 시 궁금한 점 험프리 2017.08.02 2363
261 [마이그레이션][64bit] 64비트에서 CreateFileMapping의 반환값(핸들)이 0으로 표시됩니다. 험프리 2017.01.31 2373
260 모바일 개발용 맥북 추천부탁드려요 [1] LGS 2014.11.16 2373
259 모바일 디바이스에서 실행 시 검은화면에서 멈춰버립니다. 오류를 어떻게 확인하나요? Humphery 2015.05.27 2408
258 안드로이드 스튜디오 전화걸기 기능 [1] 서태원 2017.09.06 2409
257 delphi 7.0 에서 xe6로 넘어가려고 하는데 컴포넌트 인스톨 오류 나네요. [1] 하우리 2014.05.16 2423
256 [XE8 출시세미나] RAD Studio XE8 출시세미나 질문과 답변 Humphery 2015.05.01 2424
255 델파이 10.4 patch하니 실행이 안됩니다. [7] file 갈굼정미 2021.08.26 2455
254 개발연동하는데 C# DLL로 되어있는데 이걸 참고해서 델파이로 로딩하는게 가능한가요? [1] file 다윗처럼 2016.08.08 2456
253 [세미나] 앱이 꺼져 있어도, 푸쉬가 오면 클릭하면 앱이 자동으로 뜨는것도 가능한가요? [2] Humphery 2014.08.20 2458
252 윈도우10에서 델파이7 프로젝트의 구동 가능 여부를 알고 싶습니다. [1] 차니찬 2016.05.19 2463
251 Delphi5, Paradox DB이용한 32bit 프로그램... [1] LucyKim 2014.08.19 2465
250 MySQL 모바일에서만 한글깨짐 현상. [2] file ScorpioM 2014.05.24 2480