Search code examples
c#winformslistboxselecteditemselectedindex

Set Listbox SelectedItem/Index to be the same as it was prior to moving an item out of it


I've got 2 ListBoxes and have controls to move items to and from one another. When moving an entry from listBox1 into listBox2, the first entry in listBox1 is selected automatically - logical behaviour as the item that was selected is no longer in that listBox having been moved out. However this is annoying if a user wants to add successive items as they keep having to re-select.

Code to move items from listBox1 to 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;
}

Logically I (think I) want the SelectedIndex of listBox1 to remain the same as it was prior to clicking the Add button. Practically I want the selected item in listBox1 to be the next one down. So if a user moves out item 4, the selected item should be the new item 4 (which was item 5 but is now 4), if that makes sense. Having commented out the line

listBox1.SelectedIndex = 0;

I've tried adding the line

listBox1.SelectedIndex = listBox1.SelectedIndex + 1;

to increment the index by 1 from what it was but that it makes no difference.


Solution

  • Answer as per Alina B's suggestion.

    I get the SelectedIndex and then re-set it, unless the item was the last in the listBox and therefore set it to what it was - 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;
            }
        }