【问题标题】:Focus on last entry in listbox关注列表框中的最后一个条目
【发布时间】:2011-12-08 14:37:01
【问题描述】:

我正在我的网站上创建聊天功能。 当有人输入任何文本时,我希望它显示从他进入聊天到现在的所有消息。它工作正常,一切都......

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

但是

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

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

【问题讨论】:

    标签: c# asp.net listbox chat


    【解决方案1】:
    this.ListBox1.Items.Add(new ListItem("Hello", "1"));
    this.ListBox1.SelectedIndex = this.ListBox1.Items.Count - 1;
    

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

    【讨论】:

    • 现在它只需要滚动到最后一项。
    【解决方案2】:

    使用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);
    

    附加信息 (MSDN):

    您可以使用此属性来设置项目的选择 多选ListBox。在单选中选择项目 ListBox,使用SelectedIndex 属性。

    【讨论】:

      【解决方案3】:

      当您的 ListBox 的 SelectionMode 设置为 MultiSimple 或 MultiExtended 时,您必须做一些额外的工作:

      listbox.Items.Add( message );
      
      // this won't work as it will select all the items in your listbox as you add them
      //listbox.SelectedIndex = listbox.Items.Count - 1;
      
      // Deselect the previous "last" line    
      if ( listbox.Items.Count > 1 )
          listbox.SetSelected( listbox.Items.Count - 2, false );
      // Select the current last line
      listbox.SetSelected( listbox.Items.Count - 1, true );
      // Make sure the last line is visible on the screen, this will scroll
      // the window as you add items to it
      listbox.TopIndex = listbox.Items.Count - 1;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-28
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-09
        • 2012-02-24
        相关资源
        最近更新 更多