Yaz  Font K   lt Yaz  Font B y lt

StringGrid Sütun Genişliğini Otomatik Ayarlamak

 

Merhaba arkadaşlar bu makalemizde StringGrid de sütun genişliğini otomatik ayarlayacağız.  Staff.txt dosyasındaki verileri StringGrid nesnemize yüklüyoruz. Aşağıda procedure yazılan kodlarla sütunların otomatik genişliğini belirliyoruz.

 

Resim1

 

Şekil 1

 



unit Unit1;

interface

uses

Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,

Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids;

type

TForm1 = class(TForm)

StringGrid1: TStringGrid;

procedure FormCreate(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

var

Form1: TForm1;

implementation

{$R *.dfm}

procedure PopulateStringGrid(Grid: TStringGrid; const FileName: string);

var

TextFile, Line: TStringList;

Row, col: Integer;

begin

Grid.RowCount := 0;

TextFile := TStringList.Create;

try

Line := TStringList.Create;

try

Line.Delimiter := ' ';

TextFile.LoadFromFile(FileName);

Grid.RowCount := TextFile.Count;

for Row := to TextFile.Count-do

begin

Line.DelimitedText := TextFile[Row];

for Col := to Grid.ColCount-do

if Col<Line.Count then

Grid.Cells[Col, Row] := Line[Col]

else

Grid.Cells[Col, Row] := '0';

end;

finally

Line.Free;

end;

finally

TextFile.Free;

end;

end;

//We set the automatic column size of Stringgrid

//Stringgrid in sutun genisligini otomatik ayarliyoruz

procedure AutoSizeCol(Grid: TStringGrid;

Column: integer);

var

i, W, WMax: integer;

begin

WMax := 0;

for i := to (Grid.RowCount - 1do begin

W := Grid.Canvas.TextWidth(Grid.Cells[Column, i]);

if W > WMax then

WMax := W;

end;

Grid.ColWidths[Column] := WMax + 115;

end;

procedure TForm1.FormCreate(Sender: TObject);

var

fileName:string;

i: integer;

begin

//We define 12 columns in StringGrid.

//StringGrid de 12 sutun tanimliyoruz.

StringGrid1.ColCount := 12;

// sutun genisligini ayarliyoruz.

//StringGrid1.ColWidths [0] := 80;

//We define the path to our txt file.

// txt dosyamizin yolunu tanimliyoruz.

fileName:=('D:\staff.txt');

for i := to StringGrid1.ColCount - do

AutoSizeCol(StringGrid1,i);

PopulateStringGrid(StringGrid1, fileName);

//We define the column names

// Sutun isimlerini tanimliyoruz.

StringGrid1.Cells[0,0] := 'Id';

StringGrid1.Cells[1,0] := 'FirstName';

StringGrid1.Cells[2,0] := 'LastName';

StringGrid1.Cells[3,0] := 'Contact';

StringGrid1.Cells[4,0] := 'Mail';

StringGrid1.Cells[5,0] := 'Gender';

StringGrid1.Cells[6,0] := 'Department';

StringGrid1.Cells[7,0] := 'Address';

StringGrid1.Cells[8,0] := 'PostalCode';

StringGrid1.Cells[9,0] := 'City';

StringGrid1.Cells[10,0] := 'State';

StringGrid1.Cells[11,0] := 'Country';

end;

end.      

Bir makalenin daha sonuna geldik. Bir sonraki makalede görüşmek üzere. Bahadır ŞAHİN