【问题标题】:ASP.NET UpdatePanel timer updated losing focus on textboxASP.NET UpdatePanel 计时器更新失去对文本框的关注
【发布时间】:2013-10-07 20:25:09
【问题描述】:

我的屏幕上有 2 个更新面板。一个有一个文本框,另一个是gridview。我有一个计时器(在 UpdatePanel 之外),它每 5 秒刷新一次 gridview。包含文本框的 UpdatePanel 有一个按钮(在 UpdatePanel 之外),当按下时,在文本框中输入的内容会被添加到数据库中,并且文本框会被清除,所有这些都通过 UpdatePanel(ajax,没有页面加载)。

我遇到的问题是,当链接到计时器并刷新 gridview 的 UpdatePanel 时,它会将焦点从文本框上移开。我可以通过添加 codebdehind "System.Web.UI.ScriptManager.GetCurrent(this).SetFocus(this.txtNewComment);" 来关注它但这会将光标放在文本框的开头。如果我正在输入内容,它会搞砸我正在输入的内容,因为光标位于开头而不是结尾。

关于如何在计时器触发 UpdatePanel 时将光标准确地保持在文本框中的位置有什么想法吗?

通常您会使用此处所述的文本框的 Select() 函数 (http://msdn.microsoft.com/en-us/library/ms752349.aspx),但在 ASP.NET 中似乎不存在用于 MS 按钮的 Select()。

【问题讨论】:

  • 您的计时器是否在带有 Gridview 的 UpdatePanel 中?还是在两个更新面板之外?如果它在两者之外,请尝试将其放在带有 GridView 的 UpdatePanel 内。
  • 如果我将 Timer 放在 GridView 所在的 UpdatePanel 中,则没有任何变化。

标签: c# asp.net webforms


【解决方案1】:

尝试将属性UpdateMode="Conditional" 设置为两个UpdatePanel。

在以下示例中,文本框不会失去焦点。

<asp:UpdatePanel ID="TextBoxUpdatePanel" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:TextBox ID="PanelTextBox" runat="server"></asp:TextBox>
    </ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:Literal ID="TimeLiteral" runat="server"></asp:Literal>
        <asp:Timer ID="myTimer" runat="server" OnTick="myTimer_Tick">
        </asp:Timer>
    </ContentTemplate>
</asp:UpdatePanel>

以及背后的代码

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack) {
        PanelTextBox.Focus();
        myTimer.Interval = 3000;
        myTimer.Enabled = true;
    }
}

protected void myTimer_Tick(object sender, EventArgs e)
{
    System.Threading.Thread.Sleep(2000);
    TimeLiteral.Text = DateTime.UtcNow.Ticks.ToString();
}

【讨论】:

  • 所以这行得通,但是为什么将 UpdateMode 设置为 Conditional (这就是我所做的一切。我没有将我的代码隐藏更改为你所拥有的。)有什么可以看到的焦点和光标位置情况?我不明白。
  • 当计时器计时,默认情况下页面中的所有更新面板都会刷新。将 UpdateMode 设置为 Conditional 会更改此行为。
  • 哦,等等,默认值必须是“始终”,看起来所有 UpdatePanel 都会在其中任何一个更新时更新。这导致我位于不同更新面板中的文本框得到更新,从而失去焦点。这似乎很奇怪,他们甚至会有那个“功能”。必须与嵌套的 UpdatePanel 更相关
【解决方案2】:

将 TextBox 放在 UpdatePanel 之外。

<asp:TextBox ID="PanelTextBox" runat="server"></asp:TextBox>
<asp:UpdatePanel ID="TextBoxUpdatePanel" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
      ...
    </ContentTemplate>
</asp:UpdatePanel>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 2020-06-20
    相关资源
    最近更新 更多