如何从记录中插入数据到网格

How to insert data into Grid from record

我有三个备案记录:

type
    TItem = record

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

我还有将值设置到记录中的程序:

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;

现在,我需要一个程序来将 record TItem 插入 TStringGridTGrid 和我不知道怎么做。 我的 TStringGrid 中也有三列:

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

每次当我调用程序 SetItem 时,我需要在这三列中插入三个来自记录的字段:

结果应该是这样的:

ITEM      | Quantity  | Price   

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

..等等。

首先,网格 (TGrid) 不存储数据,因此您需要提供类似 f.ex 的数据存储。 TDataArr = array of TItem;。当网格需要在单元格中显示数据时,它会调用 OnGetValue() 事件:

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;

网格中的显示隐式转换为字符串。

当您在网格中编辑数据时,更改会触发 OnSetValue 事件:

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;

似乎没有其他方式的隐式转换,因此 StrToInt(Value.AsString)StrToCurr(Value.AsString)