I have been working on ASP.net for a long time. winform has never been touched and is almost unfamiliar. Today, my colleague said that The ListBox in his winform could not be moved up or down, which made me feel strange. How is it possible? Isn't it an alternative option? It should be done by changing the location. I saw my colleague'sCodeI just thought it was a mess and I couldn't bear to read it again, so I wrote it myself. (The following code uses the extension method. The Compiler version must be greater than or equal to 3.0. You can also modify the code to a version earlier than 2.0 based on the relevant syntax)
Code Functions: Relatively simple. When an item in the ListBox is selected, click the move up button to move the item up, click the move down button, and move the item down.
[Use]
Public Static Class Listboxextension
{
Public Static Bool Moveselecteditems ( This ListBox, Bool ISUP, Action noselectaction)
{
If (ListBox. selecteditems. Count > 0 )
{
ReturnListBox. moveselecteditems (ISUP );
}
Else
{
Noselectaction ();
Return False;
}
}
Public Static Bool Moveselecteditems ( This ListBox, Bool ISUP)
{
Bool Result = True ;
ListBox. selectedindexcollection indices = ListBox. selectedindices;
If (ISUP)
{
If (ListBox. selecteditems. Count > 0 && Indices [ 0 ] ! = 0 )
{
Foreach ( Int I In Indices)
{
Result& =Moveselecteditem (ListBox, I,True);
}
}
}
Else
{
If (ListBox. selecteditems. Count > 0 && Indices [indices. Count - 1 ] ! = ListBox. Items. Count - 1 )
{
For ( Int I = Indices. Count - 1 ; I > = 0 ; I -- )
{
Result& =Moveselecteditem (ListBox, indices [I],False);
}
}
}
Return Result;
}
Public Static Bool Moveselecteditem ( This ListBox, Bool ISUP, Action noselectaction)
{
If (ListBox. selecteditems. Count > 0 )
{
ReturnMoveselecteditem (ListBox, ListBox. selectedindex, ISUP );
}
Else
{
Noselectaction ();
Return False;
}
}
Public Static Bool Moveselecteditem ( This ListBox, Bool ISUP)
{
ReturnMoveselecteditem (ListBox, ListBox. selectedindex, ISUP );
}
Private Static Bool Moveselecteditem ( This ListBox, Int Selectedindex, Bool ISUP)
{
If (Selectedindex ! = (ISUP ? 0 : ListBox. Items. Count - 1 ))
{
Object Current = ListBox. items [selectedindex];
Int Insertat = Selectedindex + (ISUP ? - 1 : 1 );
ListBox. Items. removeat (selectedindex );
ListBox. Items. insert (insertat, current );
ListBox. selectedindex = Insertat;
Return True ;
}
Return False ;
}
}
[Example]
Private Void Btnup_click ( Object Sender, eventargs E)
{
This . Listbox1.moveselecteditems ( True ,() => {
MessageBox. Show ("Select");
} );
}
Private Void Btndown_click ( Object Sender, eventargs E)
{
This . Listbox1.moveselecteditems ( False ,() => {
MessageBox. Show ("Select");
} );
}
How is the code concise and elegant? Basically, we can achieve the expected results. You can make some modifications as needed. If you have any questions, please leave a message to me!