2012-07-02 275 views
0

我遇到一個奇怪的問題,我可以將項目從一個列表框移動到另一個列表框,但不能將任何項目移回原始列表框。這裏是我的代碼:將項目從一個列表框移動到另一個列表框(c#webforms)

private void MoveListBoxItems(ListBox from, ListBox to) 
{ 
    for(int i = 0; i < first_listbox.Items.Count; i++) 
    { 
     if (first_listbox.Items[i].Selected) 
     { 
      to.Items.Add(from.SelectedItem); 
      from.Items.Remove(from.SelectedItem); 
     } 
    } 
    from.SelectedIndex = -1; 
    to.SelectedIndex = -1; 
} 

protected void Button2_Click(object sender, EventArgs e) 
{ 
    MoveListBoxItems(first_listbox, second_listbox); 
} 

protected void Button1_Click(object sender, EventArgs e) 
{ 
    MoveListBoxItems(second_listbox, first_listbox); 
} 

button2事件工作正常,但button1事件沒有。列表框不是數據綁定的,我已經手動向它們添加了項目。

也許有什麼非常明顯的,我在這裏失蹤?

感謝您的幫助提前。

回答

1

它改成這樣:

private void MoveListBoxItems(ListBox from, ListBox to) 
{ 
    for(int i = 0; i < from.Items.Count; i++) 
    { 
     if (from.Items[i].Selected) 
     { 
      to.Items.Add(from.SelectedItem); 
      from.Items.Remove(from.SelectedItem); 

      // should probably be this: 
      to.Items.Add(from.Items[i]); 
      from.Items.Remove(from.Items[i]); 
     } 
    } 
    from.SelectedIndex = -1; 
    to.SelectedIndex = -1; 
} 

你原來的方法是使用first_listbox在這兩個地方,而不是from。另外,如果選擇多個項目,我想象你的代碼不起作用。

+0

謝謝MusiGenesis。愚蠢的錯誤由我。正如他們所說的那樣,一組新的眼睛...... – Mike91

+0

NominSim還發現了另一個錯誤,如果您選擇了多個項目,這將不起作用。 – MusiGenesis

1

更改您的for循環來在本地參數from迭代,沒有特別的first_listbox

private void MoveListControlItems(ListControl from, ListControl to) 
{ 
    for(int i = 0; i < from.Items.Count; i++) 
    { 
     if (from.Items[i].Selected) 
     { 
      to.Items.Add(from.Items[i]); 
      from.Items.Remove(from.Items[i]); 
     } 
    } 
    from.SelectedIndex = -1; 
    to.SelectedIndex = -1; 
} 

你也想切換插件,如果你想一次移動多個項目中刪除。

還有一種想法,儘管它大多是個人偏好,但如果將參數類型切換爲ListControl,那麼對於ComboBox也可以使用相同的方法。

+0

感謝Nominsim的幫助。 – Mike91

相關問題