专注于列表框中的最后一个条目

Oed*_*dum 4 c# asp.net chat listbox

我正在我的网站上进行聊天功能.当有人输入任何文本时,我希望它能够显示从进入聊天到现在的所有信息.它工作正常,所有......

var query = from es in gr.chats
                            where es.timestamps > date
                            orderby es.timestamps ascending
                            select es;

                List<chat> list = new List<chat>();
                foreach (chat chat1 in query)
                {
                    list.Add(chat1);
                }

                for (int i = 0; i < list.Count; i++)
                {
                    lbChat.Items.Add("[" + list[i].timestamps + "] " + list[i].personID.ToString() + ": " + list[i].besked);
                }
Run Code Online (Sandbox Code Playgroud)

我希望我的列表框中的焦点位于我的最新条目上...我想将列表框焦点一直移动到列表框的底部.

任何人都对如何关注列表框中的最后一个条目有任何想法?

Han*_*año 10

this.ListBox1.Items.Add(new ListItem("Hello", "1"));
this.ListBox1.SelectedIndex = this.ListBox1.Items.Count - 1;
Run Code Online (Sandbox Code Playgroud)

第一行只是添加一个项目.第二个设置其SelectedIndex,它确定应该选择ListBox项目列表中的哪个项目.

  • 现在它只需要滚动到最后一个项目。 (2认同)

Jam*_*ill 8

使用 SetSelected()

//This selects and highlights the last line
[YourListBox].SetSelected([YourListBox].Items.Count - 1, true);

//This deselects the last line
[YourListBox].SetSelected([YourListBox].Items.Count - 1, false);
Run Code Online (Sandbox Code Playgroud)

其他信息(MSDN):

您可以使用此属性设置多选ListBox中的项目选择.要选择单选 ListBox中的项,请使用SelectedIndex属性.