StringGrid’de Text Dosyasındaki Verileri Göstermek
Merhaba arkadaşlar bu makalemizde Delphi’de StringGrid Nesnesinde text dosyamızdaki verileri göstereceğiz. Formumuza Palette kısmından StringGrid ekleyelim. StringGrid nesnesinin style ini DrawCell kısmından ayarliyoruz.
Şekil 1
unit stringgrid_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 StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
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 := 0 to TextFile.Count-1 do
begin
Line.DelimitedText := TextFile[Row];
for Col := 0 to Grid.ColCount-1 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;
procedure TForm1.FormCreate(Sender: TObject);
var
fileName:string;
begin
//StringGrid de 4 sutun tanimliyoruz.
StringGrid1.ColCount := 4;
// sutun genisligini ayarliyoruz.
StringGrid1.ColWidths [0] := 80;
StringGrid1.ColWidths [1] := 130;
StringGrid1.ColWidths [2] := 130;
StringGrid1.ColWidths [3] := 300;
// txt dosyamizin yolunu tanimliyoruz.
fileName:=('D:\person.txt');
PopulateStringGrid(StringGrid1, fileName);
// sutun isimlerini tanimliyoruz.
StringGrid1.Cells[0,0] := 'Id';
StringGrid1.Cells[1,0] := 'Name';
StringGrid1.Cells[2,0] := 'Surname';
StringGrid1.Cells[3,0] := 'Contact';
end;
procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
i:integer;
begin
if (ARow >= StringGrid1.FixedRows) then
with (Sender as TStringGrid).Canvas do
begin
// 1. satirin styleni ayarliyoruz.
if (ARow = 0) then
begin
Brush.Color := ClRed ;
Font.Color:=clWhite;
Font.Size:=14;
Font.Style:=[fsBold,fsItalic];
FillRect(Rect);
TextOut(Rect.Left+40, Rect.Top, StringGrid1.Cells[ACol,ARow]);
end;
// diger satirlarin styleni ayarliyoruz.
if (ARow <> 0) then
begin
Brush.Color := ClInfoBk;
Font.Color:=clNavy;
Font.Size:=12;
Font.Style:=[fsBold];
FillRect(Rect);
TextOut(Rect.Left+30, Rect.Top, StringGrid1.Cells[ACol,ARow]);
end;
end;
end;
end.
Bir makalenin daha sonuna geldik. Bir sonraki makalede görüşmek üzere. Bahadır ŞAHİN