【问题标题】:TComboBox and TListBox item Removal?TComboBox 和 TListBox 项目删除?
【发布时间】:2018-01-17 12:31:19
【问题描述】:

我正在尝试从TEdit 中给出的文本中将项目添加到TListBoxTComboBox 我的代码在 TListBox TComboBox 中添加项目时工作正常,但是当我尝试从自身和 TComobBox 中删除 TListBox 中的选定项目时,它显示访问冲突。

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

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;

【问题讨论】:

  • Button2Click() 中,交换行的顺序。然后尝试找出为什么它不适用于当前代码。
  • @TomBrunberg 是正确的。您最好在尝试删除其中任何一个之前记录要删除的项目的索引。然后按索引进行删除。
  • @TomBrunberg 哎呀!幼稚的错误。谢谢。

标签: delphi firemonkey


【解决方案1】:

进行删除的安全(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。找出来比我告诉你更有启发性。

【讨论】:

    【解决方案2】:

    此行从列表框中删除项目

    ListBox1.Items.Delete(ListBox1.Selected.Index);
    

    此行正在尝试从组合框中删除项目

    ComboBox1.Items.Delete(ComboBox1.Items.IndexOf(ListBox1.Selected.Text));
    

    但在其中您指的是 ListBox1.Selected.Text。 这是指您刚刚在第一次删除中删除的项目。 交换执行顺序应该可以:

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

    【讨论】:

      【解决方案3】:
      procedure TMainForm.Button2Click(Sender: TObject);
      begin
        if ListBox1.Selected.Index > -1 then ListBox1.Items.Delete(ListBox1.Selected.Index);
        if ComboBox1.ItemIndex > - 1 then ComboBox1.Items.Delete(ComboBox1.ItemIndex);
      end;
      

      【讨论】:

      • 我想删除在 TStringList 中索引的组合框项目(文本相同)。谢谢。
      • @bear 你应该问这个问题。
      猜你喜欢
      • 1970-01-01
      • 2017-10-09
      • 1970-01-01
      • 2023-01-20
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多