0

我有一个选中的列表框,我正在为两个按钮编写代码,一个向上移动所有选定的项目,一个向下移动每个项目。向上移动的一个工作,但我不能让另一个工作:

//Move up
        private void button2_Click(object sender, EventArgs e)
        {
            for (int i = 1; i < checkedListBox1.Items.Count; i++ ) {
                if (checkedListBox1.GetItemChecked(i)) {
                    checkedListBox1.Items.Insert(i - 1, checkedListBox1.Items[i]);
                    checkedListBox1.SetItemChecked(i - 1, true);
                    checkedListBox1.Items.RemoveAt(i + 1);
                }
            }
        }
//Move Down
        private void button3_Click(object sender, EventArgs e)
        {
            for (int i = checkedListBox1.Items.Count - 2; i >= 0; i--)
            {
                if (checkedListBox1.GetItemChecked(i))
                {
                    checkedListBox1.Items.Insert(i + 1, checkedListBox1.Items[i]);
                    checkedListBox1.SetItemChecked(i + 1, true);
                    checkedListBox1.Items.RemoveAt(i);
                }
            }
        }
4

1 回答 1

3

我认为您在第二种方法中需要这个:

checkedListBox1.Items.Insert(i + 2, checkedListBox1.Items[i]);
checkedListBox1.SetItemChecked(i + 2, true);

您当前的方法是在以下元素之前插入当前元素的副本,这基本上只是将其放在同一位置。

于 2012-04-10T05:04:41.303 回答