我有一个delete控件的问题不明白
用一个按钮实现动态生成一个控件时,怎么用另一个按钮delete掉这个控件呢?
本来我以为只要在另一个按钮里delete就行了,但是好像找不到那个新生成的控件?
//---------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm1(Owner)
{
}
//---------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
TButton *child=new TButton(this);
child->Parent=Form1;
child->Width=105;
child->Height=41;
child->Left=184;
child->Top=64;
//delete child;
}
//---------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
delete child;
}
//---------------------------------------
[解决办法]
这样你要保证删除前只点击一次 Button1(也就是只创建了一个TButton ),如果创建多次再删除的话只能删除最后一个.
[解决办法]
用一个链表或数组把动态生成的控件指针保存起来
[解决办法]
做法如下:
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm1(Owner)
{
TButton *child;
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
child=new TButton(this);
child->Parent=Form1;
child->Width=105;
child->Height=41;
child->Left=184;
child->Top=64;
//delete child;
child->Enabled= true;
}
//---------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
if(child)
{
delete child;
child= NULL;
child->Enabled= false;
}
}
[解决办法]
child= NULL;
child->Enabled= false;
???