在此代码中:
unit MSEC;
interface
uses
Winapi.Windows, Vcl.Dialogs, Vcl.ExtCtrls, System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls;
type
TMSEC = class(TWinControl)
private
FOpr :TComboBox;
public
constructor Create(AOwner: TComponent); override;
end;
implementation
const
DEF_OPERATIONS :array[0..3] of Char = ('+', '-', '*', '/');
constructor TMSEC.Create(AOwner: TComponent);
var i :Integer;
begin
inherited;
FOpr:= TComboBox.Create(Self);
with FOpr do begin
Parent:= Self;
Align:= alLeft;
Width:= DEF_OPERATIONS_WIDTH;
Style:= csDropDownList;
//error in next lines :
Items.Clear;
for i := Low(DEF_OPERATIONS) to High(DEF_OPERATIONS) do Items.Add(DEF_OPERATIONS[i]);
ItemIndex:= 0;
end;
end;
end.
当我更改ComboBox项目时,程序会中断消息:
'控制'没有父母。
如何修复此错误或以其他方式初始化ComboBox项目?
答案 0 :(得分:9)
TComboBox
需要分配的HWND才能在其Items
属性中存储字符串。要使TComboBox
获得HWND,其Parent
首先需要HWND,而其Parent
需要HWND,依此类推。问题是你的TMSEC
对象在其构造函数运行时没有分配Parent
,因此TComboBox
无法获得HWND,而是错误。
请改为尝试:
type
TMSEC = class(TWinControl)
private
FOpr: TComboBox;
protected
procedure CreateWnd; override;
public
constructor Create(AOwner: TComponent); override;
end;
constructor TMSEC.Create(AOwner: TComponent);
begin
inherited;
FOpr := TComboBox.Create(Self);
with FOpr do begin
Parent := Self;
Align := alLeft;
Width := DEF_OPERATIONS_WIDTH;
Style := csDropDownList;
Tag := 1;
end;
end;
procedure TMSEC.CreateWnd;
var
i :Integer;
begin
inherited;
if FOpr.Tag = 1 then
begin
FOpr.Tag := 0;
for i := Low(DEF_OPERATIONS) to High(DEF_OPERATIONS) do
FOpr.Items.Add(DEF_OPERATIONS[i]);
FOpr.ItemIndex := 0;
end;
end;