首页 > 解决方案 > 自动滚动到 ASP.NET 中动态生成的控件

问题描述

所以我有一个按钮,点击时会生成一个控件。它嵌套在 div 内的更新面板中,当它在 y 方向上溢出时将创建一个滚动条。目前,当我单击按钮并且它已经溢出时,将创建控件,尽管它不会滚动到它。所以好像什么都没发生。我希望滚动条向下滚动到创建控件的位置,这样它就更加用户友好。

我试过 Page.SetFocus(control) 和 control.Focus(),但都不起作用。我查看了其他帖子,但它们并没有完全解决问题,因为我生成的控件位于 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);
        }

标签: javascriptc#asp.netwebforms

解决方案


您需要在客户端调用它。添加此 AddStreamButton_Click 而不是焦点代码:

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

这将调用您已经定义的 scrollToControl 方法。


推荐阅读