简体   繁体   中英

auto scroll to dynamically generated control in ASP.NET

So I have an button that generates a control when clicked. It's nested inside an update panel inside a div, that will create a scroll bar when it overflows in the y-direction. Currently, when I click the button and it's already overflowing, the control will be created, though it will not scroll to it. So it seems like nothing happened at all. I want the scroll bar to roll down to where the control is created so it is more user-friendly.

I've tried Page.SetFocus(control) and control.Focus(), but both don't work. I've look up other posts but they don't quite solve the problem as my generated control is inside an updatePanel.

<!-- add button and dynamic control area -->
            <asp:Button ID="addStreamButton" runat="server" Text="+" OnClick="AddStreamButton_Click" Width="30px" Height="30px" Tooltip="add new stream"/>
            <div class="col-sm-6">
                <asp:UpdatePanel runat="server" ID="updatePanelPlaceholder" ChildrenAsTriggers="false" UpdateMode="Conditional"
                    style="width:650px; height:550px; overflow-y:auto; overflow-x:hidden">
                    <ContentTemplate>
                        <div class="row">
                            <asp:PlaceHolder ID="ph1" runat="server"></asp:PlaceHolder>
                        </div>
                    </ContentTemplate>
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="addStreamButton" EventName="Click" />
                    </Triggers>
                </asp:UpdatePanel>

                <script type="text/html">
                    function scrollToControl(controlName) {
                        document.getElementById(controlName).scrollIntoView();
                    }
                </script>
            </div>
protected void AddStreamButton_Click(object sender, EventArgs e)
        {
            var userControl = (DataStreamSelector)Page.LoadControl("~/DataStreamSelector.ascx");
            userControl.ID = "DynamicControl" + ControlCount;
            ControlCount++;
            ph1.Controls.Add(userControl);

            //Page.Focus(userControl);
            Page.SetFocus(userControl);
        }

You need to call it on the client side. Add this AddStreamButton_Click instead of the focus code:

ScriptManager.RegisterClientScriptBlock(this, GetType(), "none", "<script>scrollToControl('" + userControl.ID.ToString() + "');</script>", false);

That will call your scrollToControl method you already have defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM