Search code examples
javascriptjqueryasp.netdatalistdatalistitem

Scroll to a specific DataList item in a UserControl


I am working on an ASP.NET application where I have 3 user controls embedded in an aspx page which in turn uses a master page.

2 Usercontrols out of the 3 have a DataList. I would like to scroll to a specific / selected DataListItem in the usercontrol.

Also, I looked at this thread (http://forums.asp.net/t/1596201.aspx). But I don't think it will work in my case. And I have MaintainScrollPositionOnPostback="true" in the aspx page - No luck still.

It would be really helpful, if someone could help me figure out a way to do this

The markup looks something like this

     <asp:DataList ID="dl" runat="server"
            SkinID="DataList" onitemcommand="dl_ItemCommand" 
            >
            <ItemTemplate>
                <asp:Label ID="lblIDTitle" runat="server" Text="ID: " />
                <asp:Label ID="dlLabel" runat="server" Text='<%# Eval("Id") %>'  />
                <asp:LinkButton ID="btnSelect" runat="server" CommandName="Select">Select</asp:LinkButton>
                <br />
                <asp:Label ID="NameLabel" runat="server" Text='<%# Eval("DisplayName") %>' />
                <br />
            </ItemTemplate>
        </asp:DataList>

Solution

  • Looks like it is pretty simple. Here are the steps:

    • In the user control containing the datalist, added this method..

       public void FocusControlOnPageLoad(string ClientID, System.Web.UI.Page page)
       {
           ClientScriptManager clientScript = this.Page.ClientScript;
           clientScript.RegisterClientScriptBlock(this.GetType(),"CtrlFocus",
      
                          @"<script> 
      
                function ScrollView()
      
                {
                   var el = document.getElementById('" + ClientID + @"')
                   if (el != null)
                   {        
                      el.scrollIntoView();
                      el.focus();
                   }
                }
      
                window.onload = ScrollView;
      
                </script>");
      
      } 
      
    • As you can see from the mark-up I had a linkbutton. So with the OnItemCommand, I called this function whenever the link button was clicked. Something like this;

      protected void dlCommitment_ItemCommand(object source, DataListCommandEventArgs e)
      {            
          if (e.CommandName == "Select")
          {  
              LinkButton link = LinkButton)dlCommitment.Items[e.Item.ItemIndex].FindControl("btnSelectCMTMT");
               FocusControlOnPageLoad(link.ClientID, this.Page);
          }
      }
      

    And it worked like a charm. Thanks to a post that discussed about ScrollIntoView and a code project article about the method I have posted above. Since I'm on a rush, I'm not able to attach the links. Thanks to the ones who posted this information originially.