Delphi 特定代码行出现访问冲突错误
Delphi access violation error on specific line of code
我有一个从 DB table
填充的 TTreeView
。
然后我 运行 这段代码 & query
从那个 table 中的另一个 column
得到一个 value
,基于检查的 TTreeView
项目并添加它到 TMemo
.
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
test: string;
begin
for i:=0 to TreeView1.Items.Count do
begin
if TreeView1.Items[i].Checked then
begin
test := TreeView1.Items.Item[i].Text;
try
Query1.SQL.Text := 'SELECT column2 FROM someTable WHERE column1='''+test+'''';
Query1.Open;
finally
Memo1.Lines.Add(Query1.FieldByName('column2').Value);
end;
Query1.Close;
end;
end;
for i:=0 to TreeView1.Items.Count do TreeView1.Items.Item[i].Checked := false;
end;
一切正常,除了 Access Violation error
我一启动它就得到了。
Delphi 调试器将其识别为源于这行代码:
if TreeView1.Items[i].Checked then
并说:Expression illegal in evaluator
我不明白那行代码有什么问题。
愿意分享您的想法吗?
这是一个典型的菜鸟错误(我有时自己也会犯)
count 是基于 1 的,而 items 从零开始索引。所以当 i 达到 count 时你会得到一个 AV比可以索引的多 1。您需要更改此行
for i := 0 to TreeView1.Items.Count do
至
for i := 0 to TreeView1.Items.Count - 1 do
您的代码中有 2 个地方需要应用该更改。
我有一个从 DB table
填充的 TTreeView
。
然后我 运行 这段代码 & query
从那个 table 中的另一个 column
得到一个 value
,基于检查的 TTreeView
项目并添加它到 TMemo
.
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
test: string;
begin
for i:=0 to TreeView1.Items.Count do
begin
if TreeView1.Items[i].Checked then
begin
test := TreeView1.Items.Item[i].Text;
try
Query1.SQL.Text := 'SELECT column2 FROM someTable WHERE column1='''+test+'''';
Query1.Open;
finally
Memo1.Lines.Add(Query1.FieldByName('column2').Value);
end;
Query1.Close;
end;
end;
for i:=0 to TreeView1.Items.Count do TreeView1.Items.Item[i].Checked := false;
end;
一切正常,除了 Access Violation error
我一启动它就得到了。
Delphi 调试器将其识别为源于这行代码:
if TreeView1.Items[i].Checked then
并说:Expression illegal in evaluator
我不明白那行代码有什么问题。 愿意分享您的想法吗?
这是一个典型的菜鸟错误(我有时自己也会犯)
count 是基于 1 的,而 items 从零开始索引。所以当 i 达到 count 时你会得到一个 AV比可以索引的多 1。您需要更改此行
for i := 0 to TreeView1.Items.Count do
至
for i := 0 to TreeView1.Items.Count - 1 do
您的代码中有 2 个地方需要应用该更改。