2013-03-03 41 views
0

我有2個ListBox並具有用於將項目移入或移出另一個項目的控件。當將一個條目從listBox1移動到listBox2時,listBox1中的第一個條目被自動選中 - 邏輯行爲,因爲被選中的條目不再在該列表框中被移出。然而,如果用戶想要添加連續的項目,他們不得不重新選擇,這是煩人的。Set Listbox SelectedItem/Index與將項目移出項目之前的設置相同

代碼移動從listBox1中項目listBox2:

private void addSoftware() 
{ 
    try 
    { 
     if (listBox1.Items.Count > 0) 
     { 
      listBox2.Items.Add(listBox1.SelectedItem.ToString()); 
      listBox1.Items.Remove(listBox1.SelectedItem); 
     } 
    } 

    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 


    if (listBox1.Items.Count > 0) 
     listBox1.SelectedIndex = 0; 
    listBox2.SelectedIndex = listBox2.Items.Count - 1; 
} 

按道理我(我想)要listBox1中的selectedIndex保持不變之前,單擊Add按鈕,因爲它是。實際上,我希望listBox1中的選定項目成爲下一個。因此,如果用戶移出項目4,則選擇的項目應該是新項目4(這是項目5,但現在是4),如果有意義的話。已經註釋掉我已經嘗試添加行

listBox1.SelectedIndex = listBox1.SelectedIndex + 1; 

從它是什麼遞增1索引行

listBox1.SelectedIndex = 0; 

但它沒有什麼區別。

+0

爲什麼不是你以前拖累指數存儲/在將SelectedIndex重新設置爲存儲值之後,執行drop action? – 2013-03-03 03:43:31

+0

太簡單了!完美的作品 - 將用解決方案編輯第一篇文章。非常感謝你! – CSF90 2013-03-03 03:49:37

+1

發佈您的解決方案作爲答案。這是完全可以的,並且[顯式地期望](http://meta.stackexchange.com/questions/12513/should-i-not-answer-my-own-questions)在這裏。這樣,其他有類似問題的人可以看到有答案。 – pescolino 2013-03-03 03:57:47

回答

0

答案依據Alina B的建議。

我得到的SelectedIndex然後重新設置它,除非該項目是最後一個在列表框中,因此將其設置爲它是什麼 - 1

private void addSoftware() 
    { 
     int x = listBox1.SelectedIndex; 
     try 
     { 
      if (listBox1.Items.Count > 0) 
      { 

       listBox2.Items.Add(listBox1.SelectedItem.ToString()); 
       listBox1.Items.Remove(listBox1.SelectedItem); 
      } 
     } 

     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 


     if (listBox1.Items.Count > 0) 
      listBox1.SelectedIndex = 0; 
     listBox2.SelectedIndex = listBox2.Items.Count - 1; 

     try 
     { 
      // Set SelectedIndex to what it was 
      listBox1.SelectedIndex = x; 
     } 

     catch 
     { 
      // Set SelectedIndex to one below if item was last in list 
      listBox1.SelectedIndex = x - 1; 
     } 
    } 
相關問題