winforms 列表框topIndex不起作用

jrcvhitl  于 2022-11-17  发布在  其他
关注(0)|答案(4)|浏览(193)

我尝试用下面的代码将列表框的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;
}

但选定的索引却停留在列表框的底部:

这是唯一更改列表框行为的代码部分。我如何解决这个问题?

w46czmvw

w46czmvw1#

看起来对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;
}
a11xaf1n

a11xaf1n2#

如果当前SelectedIndex等于FindString的结果,则删除对当前SelectedIndex的检查,设置TopIndex的代码将始终执行

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

tez616oj3#

变更

sourceListBox.TopIndex = sourceListBox.SelectedIndex;

sourceListBox.TopIndex = index;
disbfnqx

disbfnqx4#

到winforms列表框

SendMessage(listBox.Handle,LB_SETTOPINDEX, 0, 0);

将使最上面的项目可见,保证,而不改变其选择状态,这可以是一个很好的触摸时,刚刚启动一个应用程序和反序列化加载一个列表框。

相关问题