Q&A

  • StringGrid에서 Cell에 입력제한하는 방법
Stringgrid에서 특정Cell에 데이타를 입력하는 데 조건을 주고 싶습니다.

예를 들면 10자리까지만 입력된다거나 소수점2자리를 가지는 15자리의 숫자만 입력되도록 하거나 처럼 말입니다.

방법을 아시는 분 도움 부탁드립니다.

1  COMMENTS
  • Profile
    김영대 1999.06.24 23:52
    이상준 께서 말씀하시기를...

    > Stringgrid에서 특정Cell에 데이타를 입력하는 데 조건을 주고 싶습니다.

    > 예를 들면 10자리까지만 입력된다거나 소수점2자리를 가지는 15자리의 숫자만 입력되도록 하거나 처럼 말입니다.

    > 방법을 아시는 분 도움 부탁드립니다.



    아래 source는 말씀하신 기능을 하는 예제는 아니지만

    처리하는 방법만 참고하시라고 올려둡니다



    // 수치자료를 다루는 StringGrid이므로 right aligned, floating point,

    // editable grid 가 가능합니다



    unit Unit1;



    interface



    uses

    Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,

    Grids;



    type

    TForm1 = class(TForm)

    StringGrid1: TStringGrid;

    procedure StringGrid1DrawCell(Sender: TObject; Col, Row: Integer;

    Rect: TRect; State: TGridDrawState);

    private

    { Private declarations }

    public

    { Public declarations }

    end;



    var

    Form1: TForm1;

    tmpText, cellText: String;

    i, X, Y: Integer;



    // StringGrid1의 프로퍼티 setting

    // DefaultDrawing := True

    // Options에 goEditing 추가



    implementation

    {$R *.DFM}



    procedure TForm1.StringGrid1DrawCell(Sender: TObject; Col, Row: Integer;

    Rect: TRect; State: TGridDrawState);

    begin

    if (Row > 0) and (Col > 0) and (StringGrid1.Cells[Col, Row] <> '') then

    begin

    cellText := '';

    tmpText := StringGrid1.Cells[Col, Row];

    for i := 1 to Length(tmpText) do

    if tmpText[i] in ['0'..'9','-','+','.'] then

    cellText := cellText + tmpText[i];



    try

    {cell의 값을 floating point 으로 변환}

    if cellText <> '' then

    cellText := FloatToStrF(StrToFloat(cellText),

    ffNumber,13,2); // 소숫점을 없애려면 2->0 으로

    except on EConvertError do

    begin

    cellText := '';

    end;

    end;



    if cellText = '' then

    begin

    {Set font}

    StringGrid1.Canvas.Font.Color := clRed; {잘못된 수치는 빨강}

    StringGrid1.Canvas.TextOut(Rect.Left+2, Rect.Top+2,

    StringGrid1.Cells[Col,Row]);

    end

    else

    begin

    {cell이 수치이므로 오른쪽 right-justified}

    X := Rect.Right - StringGrid1.Canvas.TextWidth(cellText);



    {cell의 수치를 bottom과 top에 대한 중앙으로}

    Y := Rect.Top + ((Rect.Bottom - Rect.Top -

    StringGrid1.Canvas.TextHeight(cellText)) div 2);

    StringGrid1.Canvas.Font.Style := StringGrid1.Canvas.Font.Style - [fsBold];



    // 오른쪽 margin을 주기위해 왼쪽으로 2 pixels 만큼 이동

    Dec(X, 2);



    StringGrid1.Canvas.TextRect(Rect, X, Y, cellText);

    end;

    end;

    end;



    end.