Reorder list box by drag and drop

Ask questions about creating Graphical User Interfaces (GUI) in PowerShell and using WinForms controls.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 4 years and 6 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
timstspry17
Posts: 45
Last visit: Tue Apr 18, 2023 2:49 pm

Reorder list box by drag and drop

Post by timstspry17 »

Hello, I am looking for help with writing a listbox control that will initially be populated with a handful of servernames. The servernames do not show up in any particular order, done on purpose, because I want to be able to rearrange the items in the list box by simply dragging them within the list box to reorder them.

Any help would be appreciated!

Tim
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Reorder list box by drag and drop

Post by jvierra »

You will have to enable drag/drop for the ListBox and write the code to manage the drag/drop events.
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Reorder list box by drag and drop

Post by jvierra »

Here is a short tutorial on how to use drag/drop with listboxes:
https://www.codeproject.com/Articles/20 ... r-s-Tutori
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Reorder list box by drag and drop

Post by jvierra »

I should also note that there is no way to use drag/drop to reorder items in a single ListBox. You would have to write custom code to select and move an item in the list order.

You can use the "MouseDown" event to select the item but getting the target will require some difficult coding that can display an insertion point while hovering. This will likely require adding some C# code helpers to the form.
User avatar
timstspry17
Posts: 45
Last visit: Tue Apr 18, 2023 2:49 pm

Re: Reorder list box by drag and drop

Post by timstspry17 »

Thanks for the information. Looks a bit more involved than I had hoped. Will probably use 2 list boxes as I have seen examples of. Doing it in a single list box would have been nice, but 2 list boxes will work too.

Tim
This topic is 4 years and 6 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked