delphi - DELPHI - 有没有办法释放在运行时创建的对象而不会出现“访问冲突”?
问题描述
这个问题让我发疯,我有一个编辑框,我在其中写了一些东西。在编辑框发生“更改”事件时,会创建一个列表框并由 SQL 查询填充。它在写作时用作提示框。当我在要选择的项目上按 Enter 键时,列表框应该“空闲”,但它继续返回“访问冲突”。这里的代码:
procedure TFTimbra.EditCommessaKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
X, Y, W: Integer;
QSugg: TAdoQuery;
begin
if not Assigned(Suggerimento) then
begin
Suggerimento := TListBox.Create(Self);
Y := EditCommessa.Top + EditCommessa.Height;
X := EditCommessa.Left;
W := EditCommessa.Width;
with Suggerimento do
begin
Top := Y;
Left := X;
Width := W;
Height := 200;
Parent := FTimbra;
BorderStyle := bsNone;
Font.Size := 14;
Font.Style := [fsBold];
end;
end else
Suggerimento.Clear;
if Key = 40 then
Suggerimento.SetFocus;
QSugg := TAdoQuery.Create(nil);
QSugg.ConnectionString := DMMain.DBConnection.ConnectionString;
QSugg.SQL.Text := format('select Codice, Descrizione from Commesse where Descrizione like %s',
[quotedstr('%' + EditCommessa.Text + '%')]);
QSugg.Open;
while not QSugg.Eof do
begin
Suggerimento.Items.Add(QSugg.FieldByName('Descrizione').AsString);
QSugg.Next;
end;
QSugg.Close;
if Assigned(Suggerimento) then Suggerimento.OnKeyDown := SuggerimentoKeyDown;
end;
这是第一部分,这是“应该”释放列表框的代码:
procedure TFTimbra.SuggerimentoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = 13 then
begin
Commessa := Suggerimento.Items[Suggerimento.ItemIndex];
EditCommessa.Text := Commessa;
Suggerimento.Free;
end;
end;
我认为问题出在 OnKeyDown 函数的调用中。提前谢谢您。
解决方案
您不能从该对象自己的事件处理程序之一销毁该对象。当事件处理程序返回时,代码继续在您刚刚释放的对象的上下文中执行。这通常会导致像这样的运行时错误。
与其使用此列表框控件的动态生命周期,不如使用表单设计器以传统方式创建它。当你想隐藏它时,设置Visible
为False
。当您希望它显示时,设置Visible
为True
。
推荐阅读
- git - 错误:未能推送一些参考 | 推送本地 git repo
- azure - Azure AD B2C - 密码更改流程
- javascript - 无法在反应应用程序中添加新的依赖项
- python - 添加多个折线图时如何更改变量名称
- c++ - 使用对话框作为主窗口。未收到 WM_INITDIALOG 消息
- javascript - 为什么我的 Android 应用程序没有在原生脚本中请求 iBeacons 的权限?
- python - Python 正则表达式中的变音符号
- linux - 没有登录铬的选项
- javascript - 全局变量在函数之外未定义
- amazon-web-services - AWS SAM - AWS::WAFv2::WebACLAssociation - AWS WAF 无法执行操作,因为您的资源不存在