Swap ListBox Items in Windows Forms  
Author Message
Aamir Iqbal





PostPosted: .NET Base Class Library, Swap ListBox Items in Windows Forms Top

hello all,

I am having a ListBox control on my Windows Form (C#).

I fill this ListBox with and ArrayList.

I have 2 buttons, Up and Down, which I am using to change the item's position in ListBox. When Up is clicked after selection an item in the ListBox, I want that the item moves at one position up and the other item(s) adjust accordingly. Ans when the down button is pressed, the selected item in the ListBox moves down and the other item(s) adjust accordingly. It is somewhat Swap like task.

I am not able to do this yet.

Anyone please help me to accomplish this job!

Thank you all,




.NET Development7  
 
 
nobugz





PostPosted: .NET Base Class Library, Swap ListBox Items in Windows Forms Top

Here's the code for moving the item up (VB I'm afraid):
If
ListView1.SelectedItems.Count <> 1 Then Exit Sub
Dim pos As Integer =
ListView1.SelectedItems(0).Index
If pos < 1 Then Exit Sub
Dim item As ListViewItem = CType(
ListView1.SelectedItems(0).Clone, ListViewItem)
ListView1.Items.RemoveAt(pos)
ListView1.Items.Insert(pos - 1, item)
item.Selected = True
item.EnsureVisible()

Code for moving it down is nearly identical. Make sure the ListView's HideSelection property = false.





 
 
Aamir Iqbal





PostPosted: .NET Base Class Library, Swap ListBox Items in Windows Forms Top

Thank you for writig to this psost!

But I am not using ListView, I am using ListBox control.

Please write code for ListBox items to move Up and also for Down.(no problem if you write in VB.NET)

I am trying my best in C# but not getting the job done.

Thanks in advance!



 
 
nobugz





PostPosted: .NET Base Class Library, Swap ListBox Items in Windows Forms Top

This will work much better in a ListView since you can keep the selected item highlighted and ensure it stays visible. Anyhoo:

If ListBox1.SelectedItems.Count <> 1 Then Exit Sub
Dim pos As Integer = ListBox1.SelectedIndex
If pos < 1 Then Exit Sub
Dim item As Object = ListBox1.SelectedItem
ListBox1.Items.Remove(item)
ListBox1.Items.Insert(pos - 1, item)
ListBox1.SelectedItem = item
ListBox1.Focus()



 
 
Aamir Iqbal





PostPosted: .NET Base Class Library, Swap ListBox Items in Windows Forms Top

Thank you nobugz for writing again!

You code was really helpful but I have finally done it before I got your 2nd reply.

Anyways, thanks for being with me and helping me!

Thanks indeed.