在不向上滚动的情况下向列表框中添加项目

Adding items to a ListBox without scrolling up

本文关键字:添加 列表 项目 滚动 情况下      更新时间:2023-09-26

我有一个包含所有在线用户的ListBox。用户从MySQL数据库加载,并每秒加载到ListBox中。当我向ListBox添加一个Item时,ListBox会向上滚动,我不希望发生这种情况。

       <asp:UpdatePanel ID="usersPanel" UpdateMode="Conditional" runat="server">
        <ContentTemplate>
          <asp:ListBox ID="lstUsers" runat="server" ViewStateMode="Enabled" AutoPostBack="True"></asp:ListBox>
          <asp:Timer ID="mainTimer" runat="server" ontick="Timer1_Tick" Interval="1000"></asp:Timer>
        </ContentTemplate>
       </asp:UpdatePanel>

计时器代码:

    protected void Timer1_Tick(object sender, EventArgs e)
    {
            ...
            MySqlDataReader datareader = command.ExecuteReader();
            if (datareader.HasRows) {
            lstUsers.Items.Clear();
            while (datareader.Read()) {
                    lstUsers.Items.Add(new ListItem(datareader.GetString(1), datareader.GetInt32(0).ToString()));}
            }
    }

我试着用javascript来做这件事,但我无法获取/设置列表框上的滚动条位置

这里要做的是在客户端的列表中保存当前选定的值,并在面板用新值更新后将其设置回。

<script type="text/javascript" language="javascript" >
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_beginRequest(beighnloadinf);        
    prm.add_endRequest(EndRequest);
    var selected = "";
    //get selected index and store in variable
    function beighnloadinf() {
     var sel = document.getElementbyId('<%=lstUsers.ClientID%>');
     var listLength = sel.options.length;
         for(var i=0;i<listLength;i++){
                 if(sel.options[i].selected){
                     selected =sel.options[i].value;
                     break;
                 }
         }
    }
    // set selected index back afrer update finished
    function EndRequest(sender, args) {
     var sel = document.getElementbyId('<%=lstUsers.ClientID%>');
            sel.value = selected;
    }
</script>

你可以做同样的事情,在代码隐藏上,你得到选定的一个,并将其放置在列表的新更新之后。

您不应该每秒都清除控件。这是你的问题:

lstUsers.Items.Clear();

最简单的解决方案是使用IEnumerable上的Except方法将ListBox items与数据源进行比较。

您必须手动将数据源转换为IEnumerable。关于如何做到这一点,请参阅本文。

注意:您必须更改扩展方法的类型。

之后,您可以循环浏览您的差异集(.Except()的返回对象),并将它们添加到您的列表框中,如下所示:

lstUsers.Items.Add("a new list item");