如何删除TlistBox的items中的某一项?(50分)

W

williem

Unregistered / Unconfirmed
GUEST, unregistred user!
有两个ListBox:ListBox1和ListBox2,在中间放了两个Button:ButtonA现在我要
达到的目的是,在选中ListBox1中的某一项按ButtonA后该项添加到ListBox2中,同时删除ListBox1
中的这个项,我用For语句来检测所选的项,想用ListBox1.items.delete(i)删除该项,但系统出错
请教如何解决?(代码)
 
listbox1.Items.Delete(listbox1.ItemIndex);
 
to williem:
这个问题好简单,只要用 ListBox1.DeleteSelected;即可
 
删除前要判断当前选择是否为空
if listbox1.itemindex<>-1 then
listbox1.items.delete(listbox1.itemindex)
 
这种情况不能使用for语句,因为删除一个item之后总数就少了,for当然会出错。
用while,实时改变index和count。
 
coldew:我用的D5在listbox中没有DeleteSelected方法
menxin和wy0311:的方法没有用!
 
procedure addAllExt(R,D:TObject); //R 来源,D,目的TListBoxi<
var
i:integer;
begin
if TListBox(R).SelCount=0 then exit;
with TListBox(R) do
for i:=1 to items.Count do
if (TListBox(R).Selected[i-1]) and
(TListBox(D).Items.IndexOf(TListBox(R).Items[i-1])<0)
then
TListBox(D).Items.Add(TListBox(R).Items[i-1]);
i:=0;
while i<TListBox(R).Items.Count do
begin
if TListBox(R).selected then
TListBox(R).Items.Delete(i);
inc(i);
end;

end;

我用DELPHI5测试了, 没有什么问题,你这样调用这个过程就可以了,
addAllExt(ListBox1,ListBox2);
 
//你出错可能是因为顺序删除选中的记录,结果出现删除的序号出错,可以逆序删除
//lbR为源,lbD为目的
if lbR.SelCount<>0 then
begin
for i := 0 to lbR.Items.Count-1 do
if lbR.Selected then
lbD.Items.Add(lbR.Items.Strings);

for i:=lbR.Items.Count-1 downto 0 do
if lbRAtt.Selected then
lbR.Items.Delete(i);
end;
 
顶部