I am adding file names from a directory in a list box which I am able to add successfully.I then should be able to arrange the files in the list box by selecting a particular item & then moving it up or down.
The below function is an attempt to move the file up. I am trying to copy entire listbox items to an object and selected listbox
items to a different object.
Then if button is pressed the selected item should be swapped with the item above to it in the list.
I intend to change the new list and copy the items back to the original listbox.But I am unaware how to copy items from object back to the listbox
The below code does not work
private void plus_Click(object sender, EventArgs e)
{
object[] items = new object[listBox1.Items.Count];
listBox1.Items.CopyTo(items, 0);
object[] selecteditems = new object[listBox1.SelectedItems.Count];
listBox1.SelectedItems.CopyTo(selecteditems, 0);
object[] selectedindices = new object[listBox1.SelectedItems.Count];
listBox1.SelectedIndices.CopyTo(selectedindices, 0);
// listBox1.Items.CopyTo(items, 0);
int upper_index = listBox1.Items.Count - 1;
for (int i = 0; i < listBox1.Items.Count;i++ )
{
if ((i == (int)selectedindices[i])&&(i!=0))
{
object temp = items[i];
items[i] = items[i - 1];
items[i - 1] = temp;
}
}
}
Copyright Notice:Content Author:「Sudarshan Taparia」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/38951357/moving-items-in-a-listbox-in-c-sharp