ListBox topIndex不起作用

时间:2014-11-28 13:36:26

标签: c# winforms listbox

我尝试使用以下代码将列表框的selectedIndex放在显示列表的顶部:

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;
}

但是所选索引卡在列表框的底部:

enter image description here

这是改变列表框行为的唯一代码部分。 我该如何解决?

3 个答案:

答案 0 :(得分:2)

sourceListBox.SelectionMode = SelectionMode.MultiExtended;的调用似乎正在重置TopIndex。在该呼叫之后设置TopIndex 将起作用:

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;
}

答案 1 :(得分:1)

取消对当前SelectedIndex的检查以及设置TopIndex将始终执行的代码,如果当前SelectedIndex等于FindString的结果

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

答案 2 :(得分:0)

更改

sourceListBox.TopIndex = sourceListBox.SelectedIndex;

sourceListBox.TopIndex = index;