form中有 label1和一个listbox1,button1,button2,label1.caption:='4.2',listbox中有很多数据项,
如果在listbox存在与label1中的数据相等的数据,点击button2就删除它
procedure TForm1.Button1Click(Sender: TObject);
var
  j:integer;
   i:real;
begin
    ListBox1.Items.Clear;
   // i:=10;
   i:=strtofloat(label1.Caption);
    for j := 0 to 7 do
    Listbox1.Items.Add (floatToStr (I+3*j));
end;procedure TForm1.Button2Click(Sender: TObject);
var
   i:integer;
begin    for i:=0 to listbox1.Items.Count-1 do
    begin
          if label1.Caption=listbox1.Items[i]  then
        begin
           listbox1.Items.Delete(i);
          // listbox1.Update;
        //   listbox1.SetFocus;
        //   ListBox1.Items.Delete(0);
        end ;
    end;
end;
button2删除出错

解决方案 »

  1.   

    大哥,你这样一定会出错的,listbox1.Items.Delete(i);执行后listbox1.Items.Count就变了,item的index就不一样了。比如listbox1.Items.Count开始为10,你删掉2个就为8了,但你的i还会到9,所以就会出错。最简单的办法就是倒着删就好了。
    procedure TForm1.Button2Click(Sender: TObject);
    var
       i,count:integer;
    begin
        count:= listbox1.Items.Count-1
        for i:=count downto 0 do
        begin
              if label1.Caption=listbox1.Items[i]  then
            begin
               listbox1.Items.Delete(i);
              // listbox1.Update;
            //   listbox1.SetFocus;
            //   ListBox1.Items.Delete(0);
            end ;
        end;
    end;试试