单价和数量输入完后,在数量单元格往任何方向移动(上下左右),金额都能自动计算。如何实现?

解决方案 »

  1.   

    不要在UI元素的事件中计算字段,你可以在单价字段和数量字段的OnChange事件中进行计算。假设数据集名称为DataSet,在数据模块中编写一个过程:
    procedure CalcMoney(Sender: TField);
    begin
      if (DataSet.State in dsEditModes) and (not DataSet.FieldByName('Qty').IsNull) and (not DataSet.FieldByName('Price').IsNull)
     then
      DataSet.FieldByName('Money').AsCurrency := DataSet.FieldByName('Qty').AsFloat * DataSet.FieldByName('Price').AsCurrency;
    end;然后在数据集的AfterOpen和BeforeClose事件中添加如下代码:
    AfterOpen:
      DataSet.FieldByName('Qty').OnChange := CalcMoney;
      DataSet.FieldByName('Price').OnChange := CalcMoney;
    BeforeClose;
      DataSet.FieldByName('Qty').OnChange := Nil;
      DataSet.FieldByName('Price').OnChange := Nil;
      

  2.   

    procedure CalcMoney(Sender: TField);
    begin
      if (Sender.DataSet.State in dsEditModes) and (not Sender.DataSet.FieldByName('Counts').IsNull)
       and (not Sender.DataSet.FieldByName('Price').IsNull)
      then 
        Sender.DataSet.FieldByName('Money').AsCurrency := Sender.DataSet.FieldByName('Counts').AsFloat * Sender.DataSet.FieldByName('Price').AsCurrency;
    end;改成这个之后,编译时提示:
    E2009 Incompatible types:'method pointer and regular procedure'
      

  3.   

    procedure TForm1.CalcMoney(Sender: TField);
    begin
      if (Sender.DataSet.FieldByName('Counts').IsNull) then
        Sender.DataSet.FieldByName('Counts').AsFloat := 0;
      if (Sender.DataSet.FieldByName('Price').IsNull) then
        Sender.DataSet.FieldByName('Price').AsCurrency := 0;
      if (Sender.DataSet.State in dsEditModes) and (not Sender.DataSet.FieldByName('Counts').IsNull)
       and (not Sender.DataSet.FieldByName('Price').IsNull)
      then
        Sender.DataSet.FieldByName('Money').AsCurrency := Sender.DataSet.FieldByName('Counts').AsFloat * Sender.DataSet.FieldByName('Price').AsCurrency;
    end;我试了,这样可以实现。
      

  4.   

    将DataSet换成你自己用的数据集的名称。