2013-03-03 59 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; 
     } 
    }