首页 文章

将Listbox SelectedItem / Index设置为与将项目移出之前相同

提问于
浏览
0

我有2个ListBoxes,并有控件来移动项目彼此之间 . 当将一个条目从listBox1移动到listBox2时,listBox1中的第一个条目会自动被选中 - 逻辑行为,因为所选项目不再位于已移出的listBox中 . 然而,如果用户想要添加连续的项目,因为他们不得不重新选择,这是令人讨厌的 .

将项目从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 = 0;

我试过添加这条线

listBox1.SelectedIndex = listBox1.SelectedIndex + 1;

将索引从它增加1,但它没有任何区别 .

1 回答

  • 0

    按照Alina B的建议回答 .

    我得到SelectedIndex,然后重新设置它,除非该项是listBox中的最后一项,因此将其设置为它是什么 - 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;
            }
        }
    

相关问题