delphi - 检查TEdit的Text属性在框架上是否为空

标签 delphi delphi-xe2

这就是我的情况。我有一个窗体(MainMenu)和一个框架(TestFrame)。 TestFrame显示在MainMenu上的TPanel上。使用此代码:

frTestFrame := TfrTestFrame.Create(nil);
frTestFrame.Parent := plMain;
frTestFrame.Align := alClient;
frTestFrame.Visible := true;


TestFrame可以正常显示,没有错误。 TestFrame上有一些TEdit框。 MainMenu上的TButton调用TestFrame中的一个过程,以检查TEdit box文本属性是否为null。

procedure TfmMainMenu.tbCheckClick(Sender: TObject);
begin
frTestFrame.Check;
end;


应该在TestFrame上使用此函数来遍历所有“ TEdit”组件,并使用GetErrorData函数(如果TEdit的text属性为null则返回一个字符串)。该字符串将添加到TStringList中,如果任何TEdit框为null,则显示该字符串。

function TfrTestFrame.Check: Boolean;
var
 ErrorList: TStringList;
 ErrorString: string;
 I: Integer;
begin
 ErrorList := TStringList.Create;
 for I := 0 to (frTestFrame.ComponentCount - 1) do
begin
  if (frTestFrame.Components[I] is TEdit) then
    begin
      ErrorString := GetErrorData(frTestFrame.Components[I]);
      if (ErrorString <> '') then
        begin
          ErrorList.Add(ErrorString);
        end;
    end;
end;
if (ErrorList.Count > 0) then
begin
  ShowMessage('Please Add The Following Information: ' + #13#10 + ErrorList.Text);
  result := false;
end;
result := true;
end;

function TfrTestFrame.GetErrorData(Sender: TObject): string;
var
 Editbox: TEdit;
 ErrorString: string;
begin
if (Sender is TEdit) then
 begin
   Editbox := TEdit(Sender);
   if (Editbox.Text <> '') then
     begin
       Editbox.Color := clWindow;
       result := '';
     end
   else
    begin
      Editbox.Color := clRed;
      ErrorString := Editbox.Hint;
      result := ErrorString;
    end;
end;
end;


问题是,当它碰到“对于I:= 0到(frTestFrame.ComponentCount-1)行时,
“它炸毁,出现错误”访问冲突在0x00458 ...读取地址0x000 ...“
我不知道为什么会发生此错误。我只能假设框架未得到创建。任何帮助都会很棒。提前致谢。

最佳答案

根据你的问题,行

for I := 0 to (frTestFrame.ComponentCount - 1) do


导致地址0x000....上的访问冲突。现在,首先,您为什么不告诉我们准确的错误消息以及全部详细信息?隐藏地址会更加困难!

无论如何,看起来该地址将是一个非常接近零的值。无论如何,关于访问冲突的唯一解释是frTestFrame无效。最有可能是nil

我注意到有问题的代码在TfrTestFrame方法内部。那么,为什么要使用frTestFrame来引用对象呢?您已经在对象的实例中。您是否有多个名为frTestFrame的全局变量?也许一个在主表单单元中,一个在框架单元中?

您应该停止对GUI对象使用全局变量。我知道IDE会引导您。抵制这种编程的诱惑。滥用全局变量会导致痛苦和折磨。

由于代码位于TfrTestFrame方法内部,因此可以使用Self。在所有TfrTestFrame方法中,删除所有对frTestFrame的引用。您的循环应如下所示:

for I := 0 to ComponentCount - 1 do


而该类中的其余方法也需要类似的处理。请注意,您无需显式编写Self,这是惯用法。

最后,我敦促您学习如何使用调试器。这是一个很棒的工具,如果您使用它,它会告诉您问题出在哪里。不要无助,让工具为您服务。

关于delphi - 检查TEdit的Text属性在框架上是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14792059/

相关文章:

delphi - 如何在TVirtualStringTree中绘制动画水平条?

delphi - 试图破解 SQLite3 并发写入的方法,有更好的方法吗?

delphi - FastMM 报告记录线程变量内存泄漏

arrays - 你如何将 Delphi 中的文件读入字节数组?

delphi - 如何将 TCanvas 包裹在现有的像素数据周围?

delphi - 为什么我在 Delphi XE2 中收到错误缺少接口(interface)方法的实现?

Delphi换行符

delphi - 如何将 TImageList 中的图片分配给 TImage?

Delphi:泛型和类型约束

datetime - 对于 TDateTime 为负值的操作,Delphi 显示奇怪的结果