-1

我在一个表单中有两个对象:1 个列表框和 1 个备忘录。我正在尝试使用以下代码删除 listbox1 中的项目和备忘录中的同一行索引:

  procedure TForm1.ListBox1KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    var i:integer; //seting a variable
    begin
    if key=vk_delete then //if key = a delete
    begin
    for i:=0  to listbox1.items.count -1   
    begin

  listbox1.DeleteSelected; //delete the selected line of the listbox
  memo2.Lines.Delete(i);   //delete the line based on the listbox selected item
    end;
    end;
        end;

但它只有在我向列表框中添加一行时才有效。如果我在列表框中添加两行并尝试删除第 2 项,则 memo1 删除第 1 行;如果我将更多项目添加到列表框中并尝试删除,则会删除 memo1 中的各种行。我认为这是因为备忘录从 0 开始索引而列表框从 1 开始。但是我无法解决这个问题。谁能帮我删除两个对象,只删除我在对象列表框中选择的行?

4

2 回答 2

2

问题只是您要从备忘录中删除多行。那是因为,出于某种原因,您编写了一个循环,该循环在循环的每次迭代中都被删除。你不想那样做。您只想删除一行。

您需要使用以下代码:

var
  Index: Integer;
....
Assert(ListBox1.Items.Count=Memo2.Lines.Count);
Index := ListBox1.ItemIndex;
if Index<>-1 then 
begin
  ListBox1.Items.Delete(Index);
  Memo2.Lines.Delete(Index);
end;

我已经替换了您的代码,该代码循环遍历列表框项目并从列表框中删除了多个项目,并从备忘录中删除了多行。相反,我获取列表框中所选项目的索引,并从列表框中进行一次删除并从备忘录中删除一行。

于 2013-05-24T16:09:55.827 回答
2

你的代码完全没有意义。它甚至没有接近做我认为你想做的事情,那就是:

创建一个新的 VCL 项目。添加一个TListBox和一个TMemo控件。在 IDE 中向它们添加相同的行(例如,alphabetagammadeltaepsilon)。

然后添加以下事件处理程序:

procedure TForm1.ListBox1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if (Key = VK_DELETE) and (ListBox1.ItemIndex <> -1) then
  begin
    Memo1.Lines.Delete(ListBox1.ItemIndex);
    ListBox1.DeleteSelected;
  end;
end;
于 2013-05-24T16:10:17.007 回答