TStringGrid

From Free Pascal wiki
Revision as of 22:02, 3 May 2016 by Abtaylr (talk | contribs)
Jump to navigationJump to search


TStringGrid is one of the Lazarus components available for use by developers. The objective of this page is to show a simple example illustrating some of the easily used properties and methods available for use.


Example StringGrid Program

It can be found typically along the upper edge of the main Lazarus window below the file menus and IDE Coolbar. You may also have it opened as a components window opened by selecting from the menu View-->Components, or, if using anchor docking opened by you as part of the Lazarus IDE. The following image shows the TStringGrid component as it may look in the Lazarus IDE:

TStringGrid01.png

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 buttons were also selected and dropped onto the form as shown. In this example it is also necessary to select an OpenDialog 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.