Introduction
This solution helps with a small but sometimes irritating problem, which may cause time loss when working on large projects. It moves listbox items up and down on the click of a button.
Using the code
First off, add a button or two, depending on what you want to achieve, to your form and set this code to the up button action:
if (listBox1.SelectedItems.Count > 0)
{
object selected = listBox1.SelectedItem;
int indx = listBox1.Items.IndexOf(selected);
int totl = listBox1.Items.Count;
if (indx == 0)
{
listBox1.Items.Remove(selected);
listBox1.Items.Insert(totl - 1, selected);
listBox1.SetSelected(totl - 1, true);
}
else{
listBox1.Items.Remove(selected);
listBox1.Items.Insert(indx - 1, selected);
listBox1.SetSelected(indx - 1, true);
}
}
And then, add this to the down button action:
if (listBox1.SelectedItems.Count > 0)
{
object selected = listBox1.SelectedItem;
int indx = listBox1.Items.IndexOf(selected);
int totl = listBox1.Items.Count;
if (indx == totl - 1)
{
listBox1.Items.Remove(selected);
listBox1.Items.Insert(0, selected);
listBox1.SetSelected(0, true);
}
else{
listBox1.Items.Remove(selected);
listBox1.Items.Insert(indx + 1, selected);
listBox1.SetSelected(indx + 1, true);
}
}
Points of Interest
For even better usability, the buttons can be disabled by default, and can be enabled when an item is selected. Furthermore, I hope this code will come in handy!
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.