TStringGrid

From Free Pascal wiki
Jump to navigationJump to search

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

TStringGrid tstringgrid.png is a component on the Additional tab of the Component Palette. A stringgrid provides a tabular display of textual information that may be edited as well.

Example StringGrid Program

To create this example create a new project in Lazarus. Select TStringGrid to add to the form, by clicking the TStringGrid component from the menu area or component window, then click on the form. In this case 2 TButtons were also selected and dropped onto the form as shown. In this example it is also necessary to select a TOpenDialog component and drop it onto the form.

TStringGrid02.png

Adjusting Columns & Changing Their Properties

Columns can be easily by added by right mouse clicking 'Columns: TGridColumns':

TStringGrid09.png

By selecting AddItem, a new column is shown below. Under the Properties tab of the Object Inspector a new list of Properties and Events relating to that column are then shown. From here the Names of the columns are set along with the width. When finished, the TreeView looks like this:

TStringGrid10.png

In this example, Button1's name was changed to ButtonAddFiles and Button2's name was changed to ButtonExit. The StringGrid1 was stretched out and the buttons were aligned as shown. Note that there is a row and a column that are of a different color. That state illustrates the concept that this row and column could be for title labels for their respective column or row. Of course this default state can be changed simply by changing the 'FixedCols' or 'FixedRows' in the Object Inspector.

TStringGrid03.png

You can see in this case that the title lines have been changed and the StringGrid1 component has been anchored. This was achieved by taking two steps. The first one involves looking at the Object Inspector and selecting various properties as needed. One step that should be taken when starting out is to carefully note the default properties. When you have made numerous changes and need to go back, it is much easier if you know what their state was when you started or at various points along the way. The state of these properties in the last image illustrates only a single fixed row with column titles. This state illustrates:

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

After viewing your work by clicking the Run button on Lazarus you may find it desirable to change these properties. In this case, the additional properties of ColClickSorts and AlternateColor were selected.

The second thing that can be done is to use the Anchor Editor (View-->AnchorEditor) to link the sides of the StringGrid to the main form.


Using Available Predefined Properties

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

Program Block To Add Data To The 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'.

CheckBox Column

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.

InsertRowWithValues Method

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.

Content based row background coloring

With PrepareCanvas event, you can alter the background color of every row based on the row's text content.

stringgridcoloring.png

const
  csPASSED = 'Passed';
  csFAILED = 'Failed';
  csERROR  = 'Error';

procedure TForm1.StatisticsGridPrepareCanvas(Sender: TObject; aCol,
  aRow: Integer; aState: TGridDrawState);
begin
  if not(sender is TStringGrid) then Exit;

  if (sender as TStringGrid).Rows[aRow].Text.Contains(csERROR) then begin
     (sender as TStringGrid).Canvas.Brush.Color := clRed;
  end else if (sender as TStringGrid).Rows[aRow].Text.Contains(csFAILED) then begin
      (sender as TStringGrid).Canvas.Brush.Color := clYellow;
  end else if (sender as TStringGrid).Rows[aRow].Text.Contains(csPASSED) then begin
      (sender as TStringGrid).Canvas.Brush.Color := clGreen;
  end;
end;

See also


LCL Components
Component Tab Components
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 • TTaskDialog • TOpenPictureDialog • TSavePictureDialog • TCalendarDialog • TCalculatorDialog • TPrinterSetupDialog • TPrintDialog • TPageSetupDialog
Data Controls TDBNavigator • TDBText • TDBEdit • TDBMemo • TDBImage • TDBListBox • TDBLookupListBox • TDBComboBox • TDBLookupComboBox • TDBCheckBox • TDBRadioGroup • TDBCalendar • TDBGroupBox • TDBGrid • TDBDateTimePicker
Data Access TDataSource • TCSVDataSet • TSdfDataSet • TBufDataset • TFixedFormatDataSet • TDbf • TMemDataset
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 • TJSONPropStorage • TIDEDialogLayoutStorage • TMRUManager • TStrHolder
LazControls TCheckBoxThemed • TDividerBevel • TExtendedNotebook • TListFilterEdit • TListViewFilterEdit • TLvlGraphControl • TShortPathEdit • TSpinEditEx • TFloatSpinEditEx • TTreeFilterEdit • TExtendedTabControl •
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 • TMySQL57Connection • 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 • TIpHtmlDataProvider • TIpHttpDataProvider • TIpHtmlPanel
Virtual Controls TVirtualDrawTree • TVirtualStringTree • TVTHeaderPopupMenu