Thursday, August 03, 2006

Order items in a ListBox


I spent some time looking for a way to rearrange the items in a list box and there my very well be a better way to do this, but this is what I came up with. I took ideas from several things I found online to arrive at this solution that best fit my needs. The "up" and "down" strings are passed in by button click events. Another little note was that in order to get the arrows to show up in the buttons I had to change the font and enable unicode. I also had to copy the symbol I wanted from the character map.

Here's the code to make it all work:

private void MoveListBoxItem(string direction)
{
switch (direction)
{
case "up":
if (productSectionBindingSource.Position!=0)
{
int OriginalIndex = productSectionBindingSource.Position;
ProductSection SectionToMove = productSectionBindingSource.Current as ProductSection;
SectionToMove.DisplayOrder = OriginalIndex - 1;
productSectionBindingSource.Remove(SectionToMove);
productSectionBindingSource.Insert(OriginalIndex - 1, SectionToMove);
productSectionBindingSource.Position = OriginalIndex;
(productSectionBindingSource.Current as ProductSection).DisplayOrder = OriginalIndex;
productSectionBindingSource.Position = OriginalIndex - 1;
}
break;
case "down":
if (productSectionBindingSource.Position != productSectionListBox.Items.Count - 1)
{
int OriginalIndex = productSectionBindingSource.Position;
ProductSection SectionToMove = productSectionBindingSource.Current as ProductSection;
SectionToMove.DisplayOrder = OriginalIndex + 1;
productSectionBindingSource.Remove(SectionToMove);
productSectionBindingSource.Insert(OriginalIndex + 1, SectionToMove);
productSectionBindingSource.Position = OriginalIndex;
(productSectionBindingSource.Current as ProductSection).DisplayOrder = OriginalIndex;
productSectionBindingSource.Position = OriginalIndex + 1;
}
break;
default:
break;
}
}

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home