TStringGrid/fr

From Free Pascal wiki
Jump to navigationJump to search

English (en) français (fr) русский (ru)

TStringGrid tstringgrid.png fournit un affichage tabulaire de données textuelles qui peuvent aussi être éditées. Le composant TStringGrid est disponible depuis l'onglet Additional de la palette de composants.

Exemple de programme avec StringGrid

Pour cet exemple, créez un nouveau projet dans Lazarus. Sélectionnez un TStringGrid à ajouter sur votre fiche, en cliquant sur l'icône du TStringGrid dans la palette de composants puis cliquez sur la fiche. Dans notre cas, deux TButton sont aussi sélectionnés et placés sur la fiche. Il faut aussi poser un TOpenDialog sur la fiche.

TStringGrid02.png

Ajustement de colonnes & modification de leurs propriétés

Des colonnes peuvent être facilement ajoutées en cliquant-droit sur 'Columns: TGridColumns' :

TStringGrid09.png

En sélectionnant AddItem, une nouvelle colonne est montrée en dessous. Sous l'onglet Propriétés de l'inspecteur d'objet, une nouvelle liste de propriétés et d'événements associés à cette colonne est alors montrée. A partir de là, les noms des colonnes sont définies ainsi que la largeur. Une fois terminé, le TreeView ressemble à cela :

TStringGrid10.png

Dans cet exemple, le nom de Button1 a été changé en ButtonAddFiles et celui de Button2 en ButtonExit. Le StringGrid1 a été étiré et les boutons ont été aligné comme montré. Remarquez qu'il y a une ligne et une colonne qui sont d'une couleur différente. L'état illustre le concept que cette colonne et cette ligne peuvent être des titres sur leurs colonne et ligne respectives. Bien sûr cet état par défaut peut être modifié en changeant simplement les propriétés 'FixedCols' ou 'FixedRows' dans l'inspecteur d'objet.

TStringGrid03.png

Vous pouvez voir dans ce cas que les lignes de titre ont été changées et que le composant StringGrid1 a été ancré. Cela a été réalisé en deux étapes. La première consiste à regarder l'inspecteur d'objet et à sélectionner diverses propriétés au besoin. Une étape qui devrait être prise lors du démarrage consiste à noter attentivement les propriétés par défaut. Lorsque vous avez effectué de nombreux changements et que vous avez besoin de revenir en arrière, il est beaucoup plus facile de savoir ce que leur état a été lorsque vous avez commencé ou à différents moments en cours de route. L'état de ces propriétés dans la dernière image ne représente qu'une seule ligne fixe avec des titres de colonne. Cet état illustre :

                 FixedCols[0], 
                 FixedRows[1], 
                 HeaderHotZones[gzFixedCols], 
                 HeaderPushZones[gzFixedCols], 
                 Options[goFixedVertLine,goFixedHorzLine,goVertLine,goHorzLine,goRangeSelect,goSmoothScroll], 
                 TitleFont[Color[clPurple]], 
                 Style[fsBold], and 
                 RowCount = 1. 

Après avoir visionné votre travail en cliquant sur le bouton Exécuter dans Lazarus, vous pourriez avoir besoin de modifier ces propriétés. Dans ce cas, les propriétés supplémentaires de ColClickSorts et AlternateColor ont été sélectionnées.

La seconde chose qui peut être faite est d'utiliser l'éditeur d'ancre (Voir-->Editeur d'ancre) pour attacher les côtés du StringGrid à la fiche principale.

Utilisation des propriétés prédéfinies disponibles

At the bottom of the Object Inspector you can find useful information about the properties shown as seen in this example:

TStringGrid04.png

To add information to the StringGrid1 component, it is necessary to either add data from a TStream, LoadCVSFile, link the grid to a database or other similar actions. If linking to a database there are other components that should be considered like the TDBGrid. Other components such as the OpenDialog may also assist using methods like the LoadCVSFile. In many cases, it is necessary to either directly link data to given cells or ranges. In our example, we will use the InsertRowWithValues method. It is now necessary to add to the ButtonAddFiles an Event by clicking the Events tab of the Object Inspector and selecting the 'OnClick' event.

TStringGrid05.png

Bloc de programme pour ajouter de la donnée dans le StringGrid

By clicking on the OnClick the SourceEditor should have added a code block for the ButtonAddFilesClick procedure. To this you should add the following code:

 uses
   Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
   Grids, LazFileUtils, LazUtf8; 
 . . . .
 types
     { TForm1 }
 TForm1 = class(TForm)
   ButtonAddFiles : TButton;
 . . . .
   procedure ButtonAddFilesClick(Sender : TObject);
   procedure ButtonExitClick(Sender : TObject); 
 . . . .
 var
   Form1 : TForm1;
 implementation
 {$R *.lfm}
 { TForm1 }  
 procedure TForm1.ButtonExitClick(Sender : TObject);
 begin
   Close;
 end;
 .
 procedure TForm1.ButtonAddFilesClick(Sender : TObject);
 var
   FilePathName : string;
 begin
   if OpenDialog1.Execute then
     FilePathName := OpenDialog1.Filename;
   AddFilesToList(FilePathName);
 end; 

The procedure for closing the application is shown for completeness. In the ButtonAddFilesClick procedure we now use the OpenDialog1 and select the Execute method. If is shown in a if - then statement where the boolean property of execute is tested. This method by default is true so the following line then when executed gives the OpenDialog1 property 'FileName' to our variable 'FilePathName'.

In the last line of procedure a new procedure is shown for 'AddFilesToList'. We now need to create this procedure. In the type declaration under either 'Public' or 'Private' we need to add this new procedure. Under implementation, the code block for the procedure is created. In this example we are going to use the files of a DVD as can be seen in this illustration:

TStringGrid06.png

We want these files to be listed upon StringGrid1.

 Type
 . . . .
 private
 procedure AddFilesToList(FilePathName : String);
 . . . .
  procedure TForm1.AddFilesToList(FilePathName : String);
  var
    D, R, K : integer;
    FileName, FilePath : string;
    SearchRec1, SearchRec2 : TSearchRec;
    FileListVideo, FileListVst : TStringList;
  begin
    FileListVideo := TStringList.Create;
    FileListVst := TStringList.Create;
    FileName := ExtractFileName(FilePathName);
    FilePath := ExtractFilePath(FilePathName);
    FileListVideo := FindAllFiles(FilePath,'VIDEO_TS.*',true, faDirectory);
    R := 1;
    K := 0;
    for D := 0 to FileListVideo.Count -1 do
    begin
      if FindFirstUtf8(FilePath, faAnyFile and faDirectory, SearchRec1)=0 then
      begin
        repeat
          With SearchRec1 do
          begin
            FileName := ExtractFileName(FileListVideo.Strings[D]);
            K := FileSizeUtf8(FileListVideo.Strings[D]);
            StringGrid1.InsertRowWithValues(R,['0', FileName, IntToStr(K)]);
            R := R + 1;
        end;
      until FindNextUtf8(SearchRec1) <> 0;
    end;
    FindCloseUtf8(SearchRec1);
  end;
  .
  FileListVst := FindAllFiles(FilePath, 'VTS_*.*', true, faDirectory);
  K := 0;
  for D := 0 to FileListVst.Count -1 do
  begin
    if FindFirstUtf8(FilePath, faAnyFile and faDirectory,SearchRec2)=0 then
    begin
      repeat
        With SearchRec2 do
        begin
          FileName := ExtractFileName(FileListVst.Strings[D]);
          K := FileSizeUtf8(FileListVst.Strings[D]);
          StringGrid1.InsertRowWithValues(R,['1', FileName, IntToStr(K)]);
          R := R + 1;
         end;
       until FindNextUtf8(SearchRec2) <> 0;
     end;
     FindCloseUtf8(SearchRec2);
   end;
   StringGrid1.SortColRow(true, 1,1,StringGrid1.RowCount-1);
   FileListVst.Free;
   FileListVideo.Free;
 end;

This example uses the methods 'FindAllFiles' from 'FileUtils' and 'FindFirstUtf8', 'FindNextUtf8' and 'FindCloseUtf8' from 'LazFileUtils'.

Colonne avec CheckBox

One feature that can be very helpful in applications of the TStringGrid is having a checkbox column that either a user can click to signify their selection or used to show a certain state for some property. Adding this type of column is illustrated in this code. In the method 'InsertRowWithValues', the first column has '0' shown in the first part of the code when files containing 'VIDEO_TS*' are being selected. The '0' is illustrating the boolean state of a checkbox with 1 being checked and 0 unchecked. In selecting from the Object Inspector under StringGrid1-->Columns: TGridColumns-->0-Select in the TreeView, the ValueChecked and ValueUnchecked are shown. You can use other numbers, or have added code to change the state.

Méthode InsertRowWithValues

In this example the method InsertRowWithValues is used to add data to our StringGrid1 component. Each column's data is entered followed by a comma. It may be necessary to use typecasting functions to get data into a string format. Variables can be referenced, or simply shown as text as our '0' and '1' are for checkbox column.

TStringGrid08.png

Upon running our new application and clicking the button 'AddFiles' a dialog box opens allowing us to select file(s) to be added. If you click on a column header, StringGrid1 is sorted in the direction as shown by the green arrow. The result should be as shown in the following illustration:

TStringGrid07.png

Depending on your needs other properties can be selected to allow editing, resizing columns, etc.

Voir aussi


Composant LCL
Onglet de palette Composants
Standard TMainMenu • TPopupMenu • TButton • TLabel • TEdit • TMemo • TToggleBox • TCheckBox • TRadioButton • TListBox • TComboBox • TScrollBar • TGroupBox • TRadioGroup • TCheckGroup • TPanel • TFrame • TActionList
Additional TBitBtn • TSpeedButton • TStaticText • TImage • TShape • TBevel • TPaintBox • TNotebook • TLabeledEdit • TSplitter • TTrayIcon • TControlBar • TFlowPanel • TMaskEdit • TCheckListBox • TScrollBox • TApplicationProperties • TStringGrid • TDrawGrid • TPairSplitter • TColorBox • TColorListBox • TValueListEditor
Common Controls TTrackBar • TProgressBar • TTreeView • TListView • TStatusBar • TToolBar • TCoolBar • TUpDown • TPageControl • TTabControl • THeaderControl • TImageList • TPopupNotifier • TDateTimePicker
Dialogs TOpenDialog • TSaveDialog • TSelectDirectoryDialog • TColorDialog • TFontDialog • TFindDialog • TReplaceDialog • TOpenPictureDialog • TSavePictureDialog • TCalendarDialog • TCalculatorDialog • TPrinterSetupDialog • TPrintDialog • TPageSetupDialog • TTaskDialog
Data Controls TDBNavigator • TDBText • TDBEdit • TDBMemo • TDBImage • TDBListBox • TDBLookupListBox • TDBComboBox • TDBLookupComboBox • TDBCheckBox • TDBRadioGroup • TDBCalendar • TDBGroupBox • TDBGrid • TDBDateTimePicker
Data Access TDataSource • TBufDataset • TMemDataset • TSdfDataSet • TFixedFormatDataSet • TDbf
System TTimer • TIdleTimer • TLazComponentQueue • THTMLHelpDatabase • THTMLBrowserHelpViewer • TAsyncProcess • TProcessUTF8 • TProcess • TSimpleIPCClient • TSimpleIPCServer • TXMLConfig • TEventLog • TServiceManager • TCHMHelpDatabase • TLHelpConnector
Misc TColorButton • TSpinEdit • TFloatSpinEdit • TArrow • TCalendar • TEditButton • TFileNameEdit • TDirectoryEdit • TDateEdit • TTimeEdit • TCalcEdit • TFileListBox • TFilterComboBox • TComboBoxEx • TCheckComboBox • TButtonPanel • TShellTreeView • TShellListView • TXMLPropStorage • TINIPropStorage • TIDEDialogLayoutStorage • TMRUManager • TStrHolder
LazControls TCheckBoxThemed • TDividerBevel • TExtendedNotebook • TListFilterEdit • TListViewFilterEdit • TTreeFilterEdit • TShortPathEdit • TLvlGraphControl
RTTI TTIEdit • TTIComboBox • TTIButton • TTICheckBox • TTILabel • TTIGroupBox • TTIRadioGroup • TTICheckGroup • TTICheckListBox • TTIListBox • TTIMemo • TTICalendar • TTIImage • TTIFloatSpinEdit • TTISpinEdit • TTITrackBar • TTIProgressBar • TTIMaskEdit • TTIColorButton • TMultiPropertyLink • TTIPropertyGrid • TTIGrid
SQLdb TSQLQuery • TSQLTransaction • TSQLScript • TSQLConnector • TMSSQLConnection • TSybaseConnection • TPQConnection • TPQTEventMonitor • TOracleConnection • TODBCConnection • TMySQL40Connection • TMySQL41Connection • TMySQL50Connection • TMySQL51Connection • TMySQL55Connection • TMySQL56Connection • TSQLite3Connection • TIBConnection • TFBAdmin • TFBEventMonitor • TSQLDBLibraryLoader
Pascal Script TPSScript • TPSScriptDebugger • TPSDllPlugin • TPSImport_Classes • TPSImport_DateUtils • TPSImport_ComObj • TPSImport_DB • TPSImport_Forms • TPSImport_Controls • TPSImport_StdCtrls • TPSCustomPlugin
SynEdit TSynEdit • TSynCompletion • TSynAutoComplete • TSynMacroRecorder • TSynExporterHTML • TSynPluginSyncroEdit • TSynPasSyn • TSynFreePascalSyn • TSynCppSyn • TSynJavaSyn • TSynPerlSyn • TSynHTMLSyn • TSynXMLSyn • TSynLFMSyn • TSynDiffSyn • TSynUNIXShellScriptSyn • TSynCssSyn • TSynPHPSyn • TSynTeXSyn • TSynSQLSyn • TSynPythonSyn • TSynVBSyn • TSynAnySyn • TSynMultiSyn • TSynBatSyn • TSynIniSyn • TSynPoSyn
Chart TChart • TListChartSource • TRandomChartSource • TUserDefinedChartSource • TCalculatedChartSource • TDbChartSource • TChartToolset • TChartAxisTransformations • TChartStyles • TChartLegendPanel • TChartNavScrollBar • TChartNavPanel • TIntervalChartSource • TDateTimeIntervalChartSource • TChartListBox • TChartExtentLink • TChartImageList
IPro TIpFileDataProvider • TIpHttpDataProvider • TIpHtmlPanel