我想用鼠标在listbox中选中一条记录,然后按键删除对应的记录
程序一
 procedure TForm2.Button2Click(Sender: TObject);
var i:integer;
begin
for i:=0  to (ListBox1.Items.Count-1)  do
  if listbox1.Selected[i] then
   listbox1.Items.Delete(i);
end;执行程序出错“list index out of bounds(14)”程序二
 procedure TForm2.Button2Click(Sender: TObject);
var i:integer;
begin
for i:=(ListBox1.Items.Count-1) downto 0 do
  if listbox1.Selected[i] then
   listbox1.Items.Delete(i);
end;
执行程序正确请都哪位高人能给指点一下,为什么会这样啊?

解决方案 »

  1.   

    你要注意ListBox1.Items.Count的变化,它会变小,但你的I还会循环,比如一开始你的ListBox1.Items.Count开始为14当你删除一个后为13所以你再调用listbox1.Selected[i]时就会出错了,你的I还会到14的。
    这是我写的,你看看
    var
      I: Integer;
    begin
      if LBSource.SelCount = 0 then exit;
      I := 0;
      while I <= LBSource.Items.Count - 1 do
      begin
        if LBSource.Selected[I] then
        begin
          LBSource.Items.Delete(I);
          I := I - 1;
        end;
        I := I + 1;
      end;
      

  2.   

    比如说你有5条记录,那么当你选中第4条,并删除之,由于for语句,i的值还要自加,但是记录数因为删除了一条,已经变成4了,就会出现错误,downto则不会出现这种情况。
      

  3.   

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      if ListBox1.ItemIndex<0 then//未选中记录
        showmessage('请选择记录')
      else//选中记录
        ListBox1.Items.Delete(ListBox1.ItemIndex);
    end;
    以上语句比你的好。
      

  4.   

    这句怎么样!  
    if listbox1.ItemHeight>0 then
        listbox1.DeleteSelected;
      

  5.   

    tjff2000(fengyun) ( ) 信誉:100  2003-09-18 11:28:00  得分:0 你的方法能一次删除几条?
      

  6.   

    procedure TForm2.Button2Click(Sender: TObject);
    var
      i: integer;
    begin
      i := 0;
      while i < ListBox1.Count do begin
        if ListBox1.Selected[i] then
          ListBox1.Items.Delete(i)
        else
          inc(i);
      end;//while
    end;
      

  7.   

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      if ListBox1.ItemIndex<0 then//未选中记录
        showmessage('请选择记录')
      else//选中记录
        ListBox1.Items.Delete(ListBox1.ItemIndex);
    end;
      

  8.   

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      if ListBox1.ItemIndex<0 then//未选中记录
        showmessage('请选择记录')
      else//选中记录
        ListBox1.Items.Delete(ListBox1.ItemIndex);
    end;