private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                listBox1.SetSelected(i, true); //选中该项
                if (listBox1.SelectedItems.Count != 0)  //如果没有选中项,则不执行
                {
                    listBox1.Items.Remove(listBox1.SelectedItem);  //移除选中项
                }
            }           
        }上面的代码,为什么listBox1的最后一项删不掉
不用给我说clear,我只想知道为什么?

解决方案 »

  1.   


            private void button1_Click(object sender, EventArgs e)
            {
                for (int i = listBox1.Items.Count-1; i >=0; i--)
                {
                    listBox1.SetSelected(i, true); //选中该项
                    if (listBox1.SelectedItems.Count != 0) //如果没有选中项,则不执行
                    {
                        listBox1.Items.Remove(listBox1.SelectedItem); //移除选中项
                    }
                } 
            }
      

  2.   


    listBox1.SetSelected(i, true); //选中该项这语句根本就是多余的。
      

  3.   

    那是因为你每次删除一项的时候 listBox1.Items.Count值会变   private void button1_Click(object sender, EventArgs e)
      {
      int count = listBox1.Items.Count;
      for (int i = 0; i < count; i++)
      {
      listBox1.SetSelected(0, true); //让每次删除的都是第一项   因为索引0每次的值都是变化的
      if (listBox1.SelectedItems.Count != 0) //如果没有选中项,则不执行
      {
      listBox1.Items.Remove(listBox1.SelectedItem); //移除选中项
      }
      }   
      }
      

  4.   

    你每移除一项listBox1.Items.Count都在变化,所以会出现项移除不掉
      

  5.   

    设置ListBox1的AutoPostBack属性设置为true,要不然循环有点小问题。