在listView中如果改变相邻两行的位置

在这篇文章中,我描述了如何用C#ListView中交换两行数据。要解决这个问题,我搜索了很多,可是始终没有找到有用的解决方法。最后,我成功地用我自己的代码实现了这个功能。

我取得所选中项上面那一项的序号(index),然后定义两个String都变量,并获得所选中项和它上面一项对值。然后赋值:把选中项的值赋给它上面的项,把上面的项的值赋给选中项。定义一个listviewItem对象:tmp,并把它们加到一个对象中。这就行了。上移按钮(upward button)的代码变到下移(downward)只需要改变一件事:把符号-变成+。这样就可以实现下移了。

上移:

private void button1_Click(object sender, EventArgs e) // upward

        {

            int index = listView1.SelectedItems[0].Index - 1;

            if (index >= 0)

            {

                string s = listView1.SelectedItems[0].Text;

                string s2 = listView1.SelectedItems[0].SubItems[1].Text;

                ListViewItem tmp = new ListViewItem(s);

                tmp.SubItems.Add(s2);

                listView1.SelectedItems[0].Text = listView1.Items[index].Text;

                listView1.SelectedItems[0].SubItems[1].Text = listView1.Items[index].SubItems[1].Text;

                listView1.Items[index] = tmp;

                ListViewItem nextItem = listView1.Items[index];

                nextItem.Selected = true;

                listView1.Items[index + 1].Selected = false;

                listView1.Focus();

                listView1.Refresh();

            }

            else

            {

                MessageBox.Show("Sorry!Can't move further upward");

            }

        }

上移:

private void button2_Click(object sender, EventArgs e)   // downward

        {

            int index = listView1.SelectedItems[0].Index + 1;

            if (index < listView1.Items.Count)

            {

                string s = listView1.SelectedItems[0].Text;

                string s2 = listView1.SelectedItems[0].SubItems[1].Text;

                ListViewItem tmp = new ListViewItem(s);

                tmp.SubItems.Add(s2);

                listView1.SelectedItems[0].Text = listView1.Items[index].Text;

                listView1.SelectedItems[0].SubItems[1].Text = listView1.Items[index].SubItems[1].Text;

                listView1.Items[index] = tmp;

                ListViewItem nextItem = listView1.Items[index];

                nextItem.Selected = true;

                listView1.Items[index - 1].Selected = false;

                listView1.Focus();

                listView1.Refresh();

            }

            else

            {

                MessageBox.Show("Sorry!Can't move further downward");

            }

        }

posted @ 2007-11-13 13:55  随风逝去(叶进)  阅读(741)  评论(0编辑  收藏  举报
Free Web Counter
Free Web Counter