Delphi cxComboBox 添加多个值并选择后返回相关值

创建表
CREATE TABLE [dbo].[Products](
    [Code] [nvarchar](20) NOT NULL,
    [Name] [nvarchar](100) NULL,
    [Price] [decimal](5, 2) NULL,
    [Quantity] [int] NULL,
    [Amount] [decimal](5, 2) NULL
)

创建测试数据

INSERT INTO Products (Code, Name, Price, Quantity, Amount) VALUES
('P001', 'Laptop', 1200.00, 50, 60000.00),
('P002', 'Smartphone', 800.00, 100, 80000.00),
('P003', 'Headphones', 50.00, 200, 10000.00),
('P004', 'Keyboard', 30.00, 150, 4500.00),
('P005', 'Mouse', 15.00, 300, 4500.00),
('P006', 'Monitor', 300.00, 80, 24000.00),
('P007', 'Printer', 150.00, 40, 6000.00),
('P008', 'External Hard Drive', 100.00, 120, 12000.00),
('P009', 'USB Flash Drive', 20.00, 250, 5000.00),
('P010', 'Wireless Router', 80.00, 90, 7200.00),
('P011', 'Tablet', 400.00, 70, 28000.00),
('P012', 'Gaming Console', 350.00, 45, 15750.00),
('P013', 'Camera', 600.00, 30, 18000.00),
('P014', 'Smart Watch', 200.00, 100, 20000.00),
('P015', 'Fitness Tracker', 80.00, 150, 12000.00),
('P016', 'Power Bank', 40.00, 200, 8000.00),
('P017', 'Bluetooth Speaker', 60.00, 120, 7200.00),
('P018', 'Drone', 1000.00, 20, 20000.00),
('P019', '3D Printer', 1500.00, 10, 15000.00),
('P020', 'Virtual Reality Headset', 800.00, 15, 12000.00);

定义记录类型 TProductInfo 和一个指向 TProductInfo 记录的指针类型 PProductInfo

type
  PProductInfo = ^TProductInfo;

  TProductInfo = record
    Code: string;
    Name: string;
    Price: Double;
    Quantity: Integer;
    Amount: Double;
  end;

填充数据到cxCombobox

procedure TForm1.FormShow(Sender: TObject);
var
  ProductInfo: PProductInfo;
begin
  cxComboBox1.Properties.Items.Clear;
  with FDQuery1 do
  begin
    close;
    sql.clear;
    sql.add('SELECT p.Code, p.Name, p.Price, p.Quantity, p.Amount FROM Products AS p');
    open;
    if RecordCount > 0 then
    begin
      first;
      while not eof do
      begin
        New(ProductInfo);
        ProductInfo.Code := FieldByName('Code').AsString;
        ProductInfo.Name := FieldByName('Name').AsString;
        ProductInfo.Price := FieldByName('Price').AsFloat;
        ProductInfo.Quantity := FieldByName('Quantity').AsInteger;
        ProductInfo.Amount := FieldByName('Amount').AsFloat;
        cxComboBox1.Properties.Items.AddObject(ProductInfo.Name, TObject(ProductInfo));
        Next;
      end;
    end;
  end;
end;

选择item后返回需要的内容

procedure TForm1.cxComboBox1PropertiesChange(Sender: TObject);
begin
  cxLabel1.Caption := cxComboBox1.EditValue;
  cxLabel2.Caption := PProductInfo(cxComboBox1.Properties.Items.Objects[cxComboBox1.ItemIndex]).Code;
  cxLabel3.Caption := PProductInfo(cxComboBox1.Properties.Items.Objects[cxComboBox1.ItemIndex]).Price.ToString;
  cxLabel4.Caption := PProductInfo(cxComboBox1.Properties.Items.Objects[cxComboBox1.ItemIndex]).Quantity.ToString;
  cxLabel5.Caption := PProductInfo(cxComboBox1.Properties.Items.Objects[cxComboBox1.ItemIndex]).Amount.ToString;
end;

效果

 

posted @ 2024-06-28 19:55  liessay  阅读(36)  评论(0编辑  收藏  举报