Search code examples
c#winformslistbox

ListBox topIndex doesn't work


I try to put the selectedIndex of a listbox at the top of the displayed list with this code :

private void textBox1_TextChanged(object sender, EventArgs e)
{
    sourceListBox.SelectionMode = SelectionMode.One;
    if (textBox1.Text != string.Empty)
    {
        int index = sourceListBox.FindString(textBox1.Text);
        if (index != -1 && sourceListBox.SelectedIndex != index)
        {
            sourceListBox.ClearSelected();
            sourceListBox.SetSelected(index, true);
            sourceListBox.TopIndex = sourceListBox.SelectedIndex;
        }
    }
    else
    {
        sourceListBox.ClearSelected();
    }
    sourceListBox.SelectionMode = SelectionMode.MultiExtended;
}

But the selected index is stuck at the bottom of the listbox :

enter image description here

And this is the only part of code that change the behavior of the listbox. How can I fix that ?


Solution

  • It looks like the call to sourceListBox.SelectionMode = SelectionMode.MultiExtended; is resetting the TopIndex. Setting the TopIndex after that call will work:

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        int topIndex = sourceListBox.TopIndex;
    
        sourceListBox.SelectionMode = SelectionMode.One;
        if (textBox1.Text != string.Empty)
        {
            int index = sourceListBox.FindString(textBox1.Text);
            if (index != -1 && sourceListBox.SelectedIndex != index)
            {
                sourceListBox.ClearSelected();
                sourceListBox.SetSelected(index, true);
                topIndex = sourceListBox.SelectedIndex;
            }
        }
        else
        {
            sourceListBox.ClearSelected();
        }
    
        sourceListBox.SelectionMode = SelectionMode.MultiExtended;
        sourceListBox.TopIndex = topIndex;
    }