Recent

Author Topic: How would you solve for this use case using a TStringGrid?  (Read 385 times)

EganSolo

  • Sr. Member
  • ****
  • Posts: 380
How would you solve for this use case using a TStringGrid?
« on: August 12, 2025, 11:58:39 pm »
You're asked to create a TStringGrid with two columns: Index and Name that must satisfy the following constraint: If the Index is even, the user can edit the name, but if it's odd, the user must pick a value from a pop-up window.

Which TStringGrid event(s) would you use to implement this functionality?

Zvoni

  • Hero Member
  • *****
  • Posts: 3135
Re: How would you solve for this use case using a TStringGrid?
« Reply #1 on: August 13, 2025, 08:27:27 am »
In OnSelectCell check if Index mod 2<>0 (or use the Odd-Function), if yes set Editor for second Column to Picklist else String?
https://lazarus-ccr.sourceforge.io/docs/lcl/grids/tcustomgrid.editor.html

EDIT:
Place a StringGrid on a Form
Set StringGrid-Options goEditing (goAlwaysShowEditor is optional)
add 2 columns

Code: Pascal  [Select][+][-]
  1. unit Unit1;
  2. {$mode objfpc}{$H+}
  3. interface
  4. uses
  5.   Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Grids, StdCtrls;
  6. type
  7.   { TForm1 }
  8.   TForm1 = class(TForm)
  9.     StringGrid1: TStringGrid;
  10.     procedure FormCreate(Sender: TObject);
  11.     procedure StringGrid1SelectCell(Sender: TObject; aCol, aRow: Integer;
  12.       var CanSelect: Boolean);
  13.   private
  14.     MyPL:TStRingList;
  15.   public
  16.   end;
  17. var
  18.   Form1: TForm1;
  19. implementation
  20. {$R *.lfm}
  21. { TForm1 }
  22. procedure TForm1.FormCreate(Sender: TObject);
  23. begin
  24.   StringGrid1.Cells[0,1]:='1';
  25.   StringGrid1.Cells[1,1]:='Test 1';
  26.   StringGrid1.Cells[0,2]:='2';
  27.   StringGrid1.Cells[1,2]:='Test 2';
  28.   StringGrid1.Cells[0,3]:='3';
  29.   StringGrid1.Cells[1,3]:='Test 3';
  30.   MyPl:=TStringList.Create;
  31.   MyPL.Add('Entry 1');
  32.   MyPL.Add('Entry 2');
  33.   MyPL.Add('Entry 3');
  34. end;
  35.  
  36. procedure TForm1.StringGrid1SelectCell(Sender: TObject; aCol, aRow: Integer;
  37.   var CanSelect: Boolean);
  38. begin
  39.   If StrToInt(StringGrid1.Cells[0,arow]) Mod 2<>0 Then
  40.      Begin
  41.        StringGrid1.Columns[1].PickList:=MyPL;
  42.        StringGrid1.Columns[1].ButtonStyle:=cbsPickList
  43.      end
  44.   Else
  45.      Begin
  46.        StringGrid1.Columns[1].PickList.Clear;
  47.        StringGrid1.Columns[1].ButtonStyle:=cbsAuto;
  48.      end;
  49. end;
  50.  
  51. end.
  52.  
« Last Edit: August 13, 2025, 02:12:58 pm by Zvoni »
One System to rule them all, One Code to find them,
One IDE to bring them all, and to the Framework bind them,
in the Land of Redmond, where the Windows lie
---------------------------------------------------------------------
Code is like a joke: If you have to explain it, it's bad

 

TinyPortal © 2005-2018