Delphi t杂物箱和TListBox物品移除?

Delphi t杂物箱和TListBox物品移除?,delphi,firemonkey,Delphi,Firemonkey,我正试图从TEdit 在TListBoxTComboBox中添加项目时,我的代码工作正常,但当我尝试从TListBox自身和TComboBox中删除所选项目时,会显示访问冲突 以下是我的代码中的过程:- procedure TMainForm.Button1Click(Sender: TObject); begin ListBox1.Items.Add(Edit1.Text); ComboBox1.Items.Add(Edit1.Text); end; procedure TMa

我正试图从
TEdit
TListBox
TComboBox
中添加项目时,我的代码工作正常,但当我尝试从
TListBox
自身和
TComboBox
中删除所选项目时,会显示访问冲突

以下是我的代码中的过程:-

procedure TMainForm.Button1Click(Sender: TObject);
begin
  ListBox1.Items.Add(Edit1.Text);   
  ComboBox1.Items.Add(Edit1.Text);
end;

procedure TMainForm.Button2Click(Sender: TObject);
begin
  ListBox1.Items.Delete(ListBox1.Selected.Index);
  ComboBox1.Items.Delete(ComboBox1.Items.IndexOf(ListBox1.Selected.Text));
end;
解决:现在解决了一个幼稚的错误。这是工作代码:

procedure TMainForm.Button2Click(Sender: TObject);
begin
  ComboBox1.Items.Delete(ComboBox1.Items.IndexOf(ListBox1.Selected.Text));
  ListBox1.Items.Delete(ListBox1.Selected.Index);      
end;
一种安全的(r)删除方法是

procedure TForm1.DeleteItems(const TextToFind : String);
var
  i1,
  i2 : Integer;
begin
  i1 := ListBox1.Items.IndexOf(TextToFind);  
  i2 := ComboBox1.Items.IndexOf(TextToFind);
  if i1 >=0 then
    ListBox1.Items.Delete(i1);
  if i2 >=0 then
    ComboBox1.Items.Delete(i2);
end;
用法:

DeleteItems(Edit1.Text);
因为这不会假设在两个列表中选择了哪些项


我让你用调试器找出你为什么得到AV。找出答案比我告诉你更有意义。

此行将从列表框中删除该项

ListBox1.Items.Delete(ListBox1.Selected.Index);
此行试图从组合框中删除该项

ComboBox1.Items.Delete(ComboBox1.Items.IndexOf(ListBox1.Selected.Text));
但在其中,您指的是列表框1.Selected.Text。 这是指您在第一次删除中删除的项目。 交换执行顺序应该可以:

begin
  ComboBox1.Items.Delete(ComboBox1.Items.IndexOf(ListBox1.Selected.Text));
  ListBox1.Items.Delete(ListBox1.Selected.Index);
end

按钮2单击()
,交换行的顺序。然后试着找出它为什么不能与当前代码一起工作。@TomBrunberg是正确的。在尝试删除任何一项之前,最好先记录要删除的项的索引。然后按索引进行删除。@TomBrunberg哎呀!开玩笑的错误。谢谢。谢谢你的回答。我想删除combobox中的项目,它在TStringList中索引(文本相同)。谢谢你。@bear你应该把这当作一个问题来问。
begin
  ComboBox1.Items.Delete(ComboBox1.Items.IndexOf(ListBox1.Selected.Text));
  ListBox1.Items.Delete(ListBox1.Selected.Index);
end