[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 457
  • Last Modified:

Moving items in a Listview object

Greetings all

I have a problem here which involves a ListView object, filled with ListViewItems. This may be a very easy problem for some of you guys on here...

What i need is a way to move the selected ListViewItem up and down in the ListView object.

I have two buttons, marked "Move up", and "Move down".

Some help would be very cool

Tchau!!

0
TheBOI
Asked:
TheBOI
  • 3
1 Solution
 
Timbo87Commented:
Here's an example using ListBox1.

Move Up:

Dim temp As Object
Dim i As Integer = ListBox1.SelectedIndex
If i - 1 < 0 Then
    Exit Sub
End If
temp = ListBox1.Items(i)
ListBox1.Items(i) = ListBox1.Items(i - 1)
ListBox1.Items(i - 1) = temp
ListBox1.SelectedIndex = i - 1

Move Down:

Dim temp As Object
Dim i As Integer = ListBox1.SelectedIndex
If i + 1 > ListBox1.Items.Count - 1 Then
    Exit Sub
End If
temp = ListBox1.Items(i)
ListBox1.Items(i) = ListBox1.Items(i + 1)
ListBox1.Items(i + 1) = temp
ListBox1.SelectedIndex = i + 1
0
 
Timbo87Commented:
C#

Move Up:

object temp;
int i = ListBox1.SelectedIndex;
if(i - 1 < 0)
       return;
temp = ListBox1.Items[i];
ListBox1.Items[i] = ListBox1.Items[i - 1];
ListBox1.Items[i - 1] = temp;
ListBox1.SelectedIndex = i - 1;

Move Down:

object temp;
int i = ListBox1.SelectedIndex;
if(i + 1 < 0)
      return;
temp = ListBox1.Items[i];
ListBox1.Items[i] = ListBox1.Items[i + 1];
ListBox1.Items[i + 1] = temp;
ListBox1.SelectedIndex = i + 1;
0
 
Timbo87Commented:
Oops, small problem in move down in C#. Here is the correct code:

Move Down:

object temp;
int i = ListBox1.SelectedIndex;
if(i + 1 > ListBox1.Items.Count - 1)
     return;
temp = ListBox1.Items[i];
ListBox1.Items[i] = ListBox1.Items[i + 1];
ListBox1.Items[i + 1] = temp;
ListBox1.SelectedIndex = i + 1;
0
 
TheBOIAuthor Commented:
Ah ok, thats great, i understand how that works.  I really should have specified that platform i am using.  

The problem is i am using VB.Net, and the control is a Listview object, not a Listbox (although i am aware they are similar).

Any chance you know how to do this for a Listview?
0
 
EBatistaCommented:
for listview the timbo's code is valid, just replace Listbox.SelectedIndex for ListView1.SelectedItem.Index
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now