2017-08-25 45 views
2

我在Windows窗體應用程序中有一個列表框。 我很容易地在列表框中上下移動單品這個腳本:C# - 如何在列表框中向上和向下移動多個項目(Windows窗體)

int newIndex = inputFiles.SelectedIndex + direction; 

if (newIndex < 0) 
    newIndex = inputFiles.Items.Count-1; 

if (newIndex >= inputFiles.Items.Count) 
    newIndex = 0; 

object selected = inputFiles.SelectedItem; 

inputFiles.Items.Remove(selected); 
inputFiles.Items.Insert(newIndex, selected); 
inputFiles.SetSelected(newIndex, true); 

我如何才能將多項選擇?謝謝你們!

+0

做同樣在一個循環? –

回答

1

如果您選擇的索引複製到一個數組,你可以遍歷項目,並適當地更新索引:

private void btnDown_Click(object sender, EventArgs e) { 
    listBox1.BeginUpdate(); 
    int[] indexes = listBox1.SelectedIndices.Cast<int>().ToArray(); 
    if (indexes.Length > 0 && indexes[indexes.Length - 1] < listBox1.Items.Count - 1) { 
    for (int i = listBox1.Items.Count - 1; i > -1; --i) { 
     if (indexes.Contains(i)) { 
     object moveItem = listBox1.Items[i]; 
     listBox1.Items.Remove(moveItem); 
     listBox1.Items.Insert(i + 1, moveItem); 
     listBox1.SetSelected(i + 1, true); 
     } 
    } 
    } 
    listBox1.EndUpdate(); 
} 

private void btnUp_Click(object sender, EventArgs e) { 
    listBox1.BeginUpdate(); 
    int[] indexes = listBox1.SelectedIndices.Cast<int>().ToArray(); 
    if (indexes.Length > 0 && indexes[0] > 0) { 
    for (int i = 0; i < listBox1.Items.Count; ++i) { 
     if (indexes.Contains(i)) { 
     object moveItem = listBox1.Items[i]; 
     listBox1.Items.Remove(moveItem); 
     listBox1.Items.Insert(i - 1, moveItem); 
     listBox1.SetSelected(i - 1, true); 
     } 
    } 
    } 
    listBox1.EndUpdate(); 
} 
1

我不認爲有一個特定的方法,在列表框中移動列表。有一個AddRange()將它全部設置到列表的底部。

您可能會嘗試製作自己的InsertRange()這樣的東西。

List<object> toInsert = new List<object>(); 
toInsert.Add(selected); 


InsertRange(int startIndex){ 
    foreach(object o in toInsert){ 
      inputFiles.Items.Insert(startIndex, o); 
      startIndex++; 
    } 
} 

這可能無法正常工作,但我認爲這可能是你要求的。

相關問題