Jande
Jande

Reputation: 1705

How to insert data into Grid from record

I have record with three filed:

type
    TItem = record

    Item    : String;
    Quantity: SmallInt;
    Price   : Currency;
 end;

Also i have procedure for setting value into record:

function TForm1.SetItem(item:string;quan:SmallInt;price:Currency):TItem;
   var It :TItem; 
   begin
          It.Item :=item;
          It.Quantity:= quan;
          It.Price:=price;
         Result :=It;
   end;

Now, i need a procedure for inserting record TItem into TStringGrid or TGrid and i do not know how to do it. I also have three columns in my TStringGrid:

1. col_Item     :string;
2. col_Quantity :SmallInt;
3. col_Price    :Currency;

Every time when i call the procedure SetItem i need to insert into this three columns three filed from record:

Result should be like this:

ITEM      | Quantity  | Price   

Bread         1         1,5
Coca cola     1         3
Fanta         2         3

..and so on.

Upvotes: 1

Views: 1743

Answers (1)

Tom Brunberg
Tom Brunberg

Reputation: 21033

First, the grid (TGrid) doesn't store data so you need to provide a data storage like f.ex. TDataArr = array of TItem;. When the grid needs data to show in a cell, it calls the OnGetValue() event:

procedure TForm4.Grid1GetValue(Sender: TObject; const Col, Row: Integer;
  var Value: TValue);
begin
  if Row > (Length(DataArr)-1) then exit;
  case Col of
    0: Value := DataArr[Row].Item;
    1: Value := DataArr[Row].Quantity;
    2: Value := DataArr[Row].Price;
  end;
end;

There is an implicit conversion to string for the disply in the grid.

When you edit data in the grid, the change triggers the OnSetValue event:

procedure TForm4.Grid1SetValue(Sender: TObject; const Col, Row: Integer;
  const Value: TValue);
begin
  if Row > (Length(DataArr)-1) then exit;
  case Col of
    0: DataArr[Row].Item := Value.AsString;
    1: DataArr[Row].Quantity := StrToInt(Value.AsString);
    2: DataArr[Row].Price := StrToCurr(Value.AsString);
  end;
end;

There doesn't seem to be an implicit conversion the other way, therefore the StrToInt(Value.AsString) and StrToCurr(Value.AsString).

Upvotes: 1

Related Questions