ListBox selection

2

Every time you move an item up or down a listBox it loses the focus of the item.

I can not always focus on the item.

For example: suppose my list has 200 items. So I want to move the item that is in position 160 to the 159, so once moved it loses its selection (focus), if you want to move from 159 to 158 I will have to click on the item again and select.

public void MoveItem(int direction)
{            
    if (listBox.SelectedItem == null || listBox.SelectedIndex < 0)
        return; 

    int newIndex = listBox.SelectedIndex + direction;

    if (newIndex < 0 || newIndex >= listBox.Items.Count)
        return; 

    object selected = listBox.SelectedItem;

    listBox.Items.Remove(selected);

    listBox.Items.Insert(newIndex, selected);     
}
    
asked by anonymous 27.07.2017 / 15:19

3 answers

2

After moving the item, place the item as the one selected through your index .

listBox.SelectedIndex = newIndex;

If you do not have access to the desired index, save it to a class variable.

    
27.07.2017 / 15:30
2

You can use listBox.SetSelected() to select the item back:

public void MoveItem(int direction)
{            
    if (listBox.SelectedItem == null || listBox.SelectedIndex < 0)
        return; 

    int newIndex = listBox.SelectedIndex + direction;

    if (newIndex < 0 || newIndex >= listBox.Items.Count)
        return; 

    object selected = listBox.SelectedItem;

    listBox.Items.Remove(selected);

    listBox.Items.Insert(newIndex, selected);

    listBox.SetSelected(newIndex, true); //Ta aqui o bixo
}

If you have questions, take a look at documentation .

    
27.07.2017 / 15:30
2

I was able to solve the problem

listBox.Focus();
listBox.SelectedIndex = newIndex;

I inserted the focus at the end of the code and then selected a new index.

    
27.07.2017 / 15:55