[英]Moving items in a listbox in c#
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;
}
}
}
At first sight it should not work because you're creating a new a list and not changing the actual DataSource
for the ListBox
. 乍一看,它不起作用,因为您正在创建一个新列表,而不是更改ListBox
的实际DataSource
。 You need to move the items inside the DataSource
itself, or you need to perform all that actions on a separate list and at the end, set the DataSource
again. 您需要在DataSource
本身内部移动项目,或者需要在单独的列表上执行所有这些操作,最后,再次设置DataSource
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.