【问题标题】:How to set Focus to a TextBox from codebehind when there is postback involved?当涉及回发时,如何从代码隐藏将焦点设置为文本框?
【发布时间】:2013-11-02 19:26:17
【问题描述】:

我有一个数据输入网络表单,其中有一些文本框会导致 textchanged 事件的回发。我将焦点设置到所需的文本框,然后通过使用... TextBox2.Focus() 但这只适用于 Visual Studio 2010 而不是 2005。它不会给出任何错误或任何东西,但焦点会在几分之一秒内进入 textBox2 然后消失(可能是由于回发)。 注意:我必须只从代码后面设置焦点!如果需要,我已经准备好使用 JavaScript,但它必须从后面的代码运行。

【问题讨论】:

    标签: c# javascript asp.net vb.net


    【解决方案1】:

    尝试下面的 VB.NET 代码在 Postback 之后添加 javascript 到加载的页面:

    ClientScript.RegisterStartupScript(Me.GetType(), "Set TB Focus", "document.getElementById('" & TextBox2.ClientID & "').focus();", True)
    

    这将在回发时将脚本写入页面,然后执行(因为它不在函数中)并设置文本框的焦点。

    还有 C# 代码:

    ClientScript.RegisterStartupScript(this.GetType(), "Set Tb Focus", "document.getElementById('" & TextBox2.ClientID & "').focus();", true);
    

    【讨论】:

      【解决方案2】:

      试试:

      ClientScript.RegisterStartupScript(typeof(this), "Focus",
      String.Format("document.GetElementById('{0}').focus;", txt.ClientID), true);
      

      它注册一个javascript并聚焦它。

      【讨论】:

        【解决方案3】:
               ClientScript.RegisterStartupScript(this.GetType(), "focus", "document.getElementById('" + txtYourControlName.ClientID + "').focus();", true);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-07-23
          • 2012-10-05
          • 2014-01-22
          • 1970-01-01
          相关资源
          最近更新 更多