用一个按钮对两个listbox作删除操作,怎么实现?(怎样解决listbox index out of bounds(-1))
谢谢!!!

解决方案 »

  1.   

    先判断他的listbox的item数量。建议贴一下代码
      

  2.   

    我的原代码如下:怎样解决listbox index out of bounds(-1)的问题???
    if  (ListBox1.Count=0) and (ListBox2.Count=0) then
            MessageDlg('不存在!', mtInformation,[mbOk], 0);
          if ((ListBox1.Count>0) or (ListBox2.Count>0)) and ((ListBox1.ItemIndex=-1) and (ListBox2.ItemIndex=-1)) then
            MessageDlg('请选择!', mtInformation,[mbOk], 0)
          else
          begin
           if (Listbox1.Selected[listbox1.ItemIndex]) and  (Listbox2.Selected[listbox2.ItemIndex]) then
            MessageDlg('不能同时选中!', mtInformation,[mbOk], 0)
           else if ListBox1.Selected[listbox1.ItemIndex] then
            begin
               listbox1.Items.Delete(listbox1.itemindex);
               listbox1.Update;
               listbox1.SetFocus;
            end
           else      
             begin
               listbox2.Items.Delete(listbox2.itemindex);
               listbox2.Update;
               listbox2.SetFocus;
            end
          end
      

  3.   

    可以设置HideSelection := False,
    要删除ListBox要注意Items的个数,删了第一个之后,Items.Count已经变了,因此建议这样删
    while ListBox.Items.Count > 0 do
    begin
      //do something...
      ListBox.Items.Delete(0);
    end;
      

  4.   

    if (ListBox1.ItemIndex <> -1) and (ListBox2.ItemIndex <> -1) then
        MessageDlg('不能同时选中!', mtInformation,[mbOk], 0)
      else if ListBox1.ItemIndex <> 0 then
        ListBox1.Items.Delete(ListBox1.ItemIndex)
      else if ListBox2.ItemIndex <> 0 then
        ListBox2.Items.Delete(ListBox2.ItemIndex)
      else if (ListBox1.Items.Count = 0) and (ListBox2.Items.Count = 0) then
        MessageDlg('不存在!', mtInformation,[mbOk], 0)
      else MessageDlg('请选择!', mtInformation,[mbOk], 0);
      

  5.   

    不好意思,应该是<>-1
      if (ListBox1.ItemIndex <> -1) and (ListBox2.ItemIndex <> -1) then
        MessageDlg('不能同时选中!', mtInformation,[mbOk], 0)
      else if ListBox1.ItemIndex <> -1 then
        ListBox1.Items.Delete(ListBox1.ItemIndex)
      else if ListBox2.ItemIndex <> -1 then
        ListBox2.Items.Delete(ListBox2.ItemIndex)
      else if (ListBox1.Items.Count = 0) and (ListBox2.Items.Count = 0) then
        MessageDlg('不存在!', mtInformation,[mbOk], 0)
      else MessageDlg('请选择!', mtInformation,[mbOk], 0);
      

  6.   

    我以前也遇到过类似的问题,很可能ListBox1与ListBox2中Items的个数变了导致错误。举个例子:对ListBox2做删除操作,但ListBox2中已无记录,你在程序中无容错性判断,导致系统提示出错。同意q3ares(血人偶)的看法。相信我,没错的,不信你可以跟踪一下。
      

  7.   

    他只要删除选中的那一个。判断ItemIndex就行了,不管是没有选中还是对象个数为0,ItemIndex都是-1。