TAdvStringGrid

Example 73 : Using the ICellGraphic interface for cells

Using a lookup combobox in TAdvStringGrid
vcl grid

Sometimes it is desirable to display a different value from the real value that you want to internally manage in the grid and to change this value with a combobox that displays these different values but still updates the grid correct with internally used values.

In TAdvStringGrid, it is easy to display a value different from the real cell text using the event OnGetDisplText. This event is triggered whenever a cell needs to be painted and queries the actual text to display. For the ease of coding, in this sample the OnGetDisplText will display a string that is stored in the grid's combobox items list based on a numeric value that is stored in the grid cell.

The grid's combobox items is initialized with:

procedure TForm1.FormCreate(Sender: TObject);
begin
  advstringgrid1.ComboBox.Items.AddObject('Germany', TObject(0));
  advstringgrid1.ComboBox.Items.AddObject('France', TObject(1));
  advstringgrid1.ComboBox.Items.AddObject('Spain', TObject(2));
  advstringgrid1.ComboBox.Items.AddObject('Russia', TObject(3));
end;

and the OnGetDisplText simply replaces a numeric value between 0 & 3 to the corresponding item in the combobox:

procedure TForm1.AdvStringGrid1GetDisplText(Sender: TObject; ACol,
ARow: Integer; var Value: string);
var
i,e: integer;
begin
val(value, i, e);

if e = 0 then
Value := advstringgrid1.ComboBox.Items[StrToInt(Value)];
end;

As inplace editor, the edComboList editor is specified with:

procedure TForm1.FormCreate(Sender: TObject);
begin
  advstringgrid1.Options := advstringgrid1.Options + [goEditing];
  advstringgrid1.DefaultEditor := edComboList;
end;

This inplace editor will automatically display its items in its dropdown list. By default, the value with which the cell is updated with the text value of the combobox. In this example, we need to set the grid cell value to the corresponding numeric value though instead of the text. This can be done using the OnCellValidate event that is triggered when editing ends with following code:

procedure TForm1.AdvStringGrid1CellValidate(Sender: TObject; 
	ACol, ARow: Integer; var Value: string; var Valid: Boolean);
begin
  Value := IntToStr(integer(advstringgrid1.ComboBox.Items.Objects[advstringgrid1.ComboBox.ItemIndex]));
end;

Delphi project & source files for downloading included in the main demos distribution for Delphi.