2013-09-24 34 views
0

在此代碼:「控件沒有父」,在創建組合框

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項目?

回答

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; 
+0

這是彈性的窗口娛樂?這就是Tag的用途嗎? –

+0

@DavidHeffernan,初始化項目只有一次。但是當我測試它沒有使用標籤,它的工作正確! – MohsenB

+1

如果窗口被重新創建,則不會。雷米應該解釋。 –