Solved

Setting focus on a text box

Posted on 2004-10-20
23
879 Views
Last Modified: 2008-02-07
How do I set focus on a text box in C#?
0
Comment
Question by:RosanneParnell
  • 7
  • 5
  • 4
  • +1
23 Comments
 
LVL 3

Expert Comment

by:aacool
ID: 12359965
Use

textBox1.Select()

The overloads allow you to specify a tab order or even text to select within the textbox
0
 

Author Comment

by:RosanneParnell
ID: 12360406
I got the following error: 'System.Web.UI.WebControls.TextBox' does not contain a definition for 'Select'
0
 
LVL 3

Expert Comment

by:aacool
ID: 12360470
Ah - you are using ASP.NET - The method is available only with System.Windows.Forms.TextBox

Just a sec...
0
Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

 
LVL 3

Expert Comment

by:aacool
ID: 12360670
You can use some script like

document.forms["form-name"].elements["text-box-name"].focus();

in your asp file. you can have a function like
function setFocus()
{
    document.forms["form-name"].elements["text-box-name"].focus();
}


See if this helps.
0
 
LVL 3

Expert Comment

by:aacool
ID: 12360674
That's javascript, btw
0
 

Author Comment

by:RosanneParnell
ID: 12360804
Actually, I have a C# file as my codebehind because I'm using C#.NET. Can I use javascript here?
0
 
LVL 8

Expert Comment

by:tomvergote
ID: 12361007
You should use a page.registerstartupscript so your form element names match.

have a look at my posts in this thread:
http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/Q_21163539.html

or the article I linked to then
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebUIControlClassClientIDTopic.asp
0
 
LVL 8

Expert Comment

by:tomvergote
ID: 12361027
0
 
LVL 3

Expert Comment

by:aacool
ID: 12361143
You can call javascript from your codebehind C# program as well.

One way is:

document.parentWindow.execScript("javascriptstring","JavaScript");

where javascriptstring = "
function setFocus()
{
    document.forms["form-name"].elements["text-box-name"].focus();
}
"

Make sure you replace the form name, textboxname, etc with your real values
0
 
LVL 3

Expert Comment

by:aacool
ID: 12361229
Actually, use the following

RegisterClientScriptBlock(key, script)
The RegisterClientScriptBlock method adds a block of client-side script after the Web Form's rendered <form> element, before any Web controls contained within the Web Form. The key input parameter allows you to specify a unique key associated with this script block, whereas the script parameter includes the complete script code to emit. (This script parameter should include the actual <script> element, along with the client-side JavaScript or Microsoft VBScript.)

e.g.
    RegisterClientScriptBlock("setFocus-function", _
            "<script language=""JavaScript"">" & vbCrLf & _
            "function setFocus(id) {" & _
            "  var o = document.getElementById(id); " & _
            "if (o != null) o.focus(); " & _
            "}" & vbCrLf & _
            "</script>")

To call this from your C# codebehind file:

private void SetFocusBtnClicK(object sender, System.EventArgs e)
{
  setFocus(textBox1)
}
0
 
LVL 3

Expert Comment

by:Realmrat
ID: 12367341
The question has been anwsered, though just a tip.  Create your own custom Page, that inherits from the .NET page class.  Then include this focus script as a property or function available to that class.  Then have all of your pages inherit from your custom class, instead of the default .NET class.  That way this functionality is available to all your pages if you ever need it, and don't have to register the script each time.  It's real handy.  I've made ones for focusing on controls, setting the title, and poping up new windows sending dynamic parameters.  They're slick and easy to use.


 - Joe
0
 

Author Comment

by:RosanneParnell
ID: 12370444
Where does the javascript reside.

   RegisterClientScriptBlock("setFocus-function", _
            "<script language=""JavaScript"">" & vbCrLf & _
            "function setFocus(id) {" & _
            "  var o = document.getElementById(id); " & _
            "if (o != null) o.focus(); " & _
            "}" & vbCrLf & _
            "</script>")
0
 
LVL 8

Expert Comment

by:tomvergote
ID: 12371411
that piece of code will inject your script in the html source, try it and do a view source on the resulting page
0
 

Author Comment

by:RosanneParnell
ID: 12371529
No, I'm asking where do I put the RegisterClientScriptBlock paragraph? In the codebehind page? In the HTML of the .aspx page?
0
 
LVL 8

Expert Comment

by:tomvergote
ID: 12371548
in the cs file (codebehind)
I usually put it in my page.onload
0
 

Author Comment

by:RosanneParnell
ID: 12371822
Okay, great - thanks!

Now when I added the call to setFocus, I got the following error:

C:\VSProjects\ManhattanApps\ActuatorDesignerSolution\ActuatorDesigner\Login.aspx.cs(65): The name 'setFocus' does not exist in the class or namespace 'Actuator1.Login'


I placed it right after the RegisterClientScriptBlock paragraph in Page_Load. What am I doing wrong here?
0
 
LVL 3

Expert Comment

by:aacool
ID: 12377087
Can you post your relevant functions?
0
 
LVL 3

Expert Comment

by:Realmrat
ID: 12377246
I'm working up a small example to show how to register Javascript in a Custom Class, and use that class on a Page.  Functions will include Focus, Title, and PopUp.


 - Joe
0
 
LVL 3

Accepted Solution

by:
Realmrat earned 500 total points
ID: 12378018
Okay, this is built upon a class that Dino Esposito first built in his book "Programming ASP.NET".  The refresh module was  then added in a MSDN article "Build Your ASP.NET Pages on a Richer Bedrock".  I'll show some experts from the entire code.  The refresh module is a rather "Advanced" technique.  Refer to the MSDN article to get a full understanding.

Programming ASP.NET - Amazon:
http://www.amazon.com/exec/obidos/ASIN/0735619034/qid=1098419898/sr=2-3/ref=pd_ka_b_2_3/103-1885929-3411816

MSDN Article:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvs05/html/bedrockaspnet.asp


                           Custom Page Class Snippet:
|-------------------------------------------------------------------------------

using System;
using System.Web.UI;
using System.Web;
using System.Text;


namespace Msdn
{
      public class Page : System.Web.UI.Page  //<-- Notice inheriting from base Page
      {
            #region Constants

            // ***********************************************************
            // Constants
            public const string  RefreshTicketCounter = "RefreshTicketCounter";
            private const string FocusFunctionName = "__setFocus";
            private const string FocusScriptName = "__inputFocusHandler";
                private const string TitleFunctionName = "__setTitle";
                private const string TitleScriptName = "__inputTitleHandler";
                private const string PopUpFunctionName = "__popWindow";
                private const string PopUpScriptName = "__popWindowHandler";
            // ***********************************************************


            #endregion


            // ***********************************************************
        /// <summary>
        /// Page Constructor
        /// </summary>
            public Page()
            {
                  m_focusedControl = "";

                  // Register a PreRender handler
                  this.PreRender += new EventHandler(RefreshPage_PreRender);
            }
            // ***********************************************************

        #region Properties
            // **************************************************************
            /// <summary>
            /// Indicates if the page is being viewed in response to F5 hit
            /// </summary>
            public bool IsPageRefresh
            {
                  get
                  {
                        object o = HttpContext.Current.Items[RefreshAction.PageRefreshEntry];
                        if (o == null)
                              return false;
                        return (bool) o;
                  }
            }
            // **************************************************************

            
            
            // **************************************************************
        /// <summary>
        /// Gets or sets the control with the input focus
        /// </summary>
        public string Focus
        {
            get
            {
                return m_focusedControl;
            }
            set
            {
                m_focusedControl = value;
            }
        }
        // **************************************************************

        // **************************************************************
        //TODO: Filter out '/" etc
        /// <summary>
        /// Gets or sets the Title of the form upon loading
        /// </summary>
        public string Title
        {
            get
            {
                if(m_PageTitle != null)
                {
                    return m_PageTitle;
                }
                else
                {
                    return String.Empty;
                }
            }
            set
            {
                m_PageTitle = value;
            }
        }
            // **************************************************************

        // **************************************************************
        private string PopUpUrl
        {
            get
            {
                if(m_PopUpUrl != null)
                    return m_PopUpUrl;
                else
                    return String.Empty;
            }
            set
            {
                if(value != "" | value != null)
                {
                    m_PopUpUrl = value;
                }
            }
        }
        // **************************************************************

        // **************************************************************
        private string PopUpValue
        {
            get
            {
                if(m_PopUpValue != null)
                    return m_PopUpValue;
                else
                    return String.Empty;
            }
            set
            {
                if(value != "" | value != null)
                {
                    m_PopUpValue = value;
                }
            }
        }
        // **************************************************************

        #endregion

       
        #region Public Methods
        // **************************************************************
        /// <summary>
        /// Increase the internal counter used to generate refresh tickets
        /// *NOTE* this function must be used to track a Page Refresh
        /// </summary>
        public void TrackRefreshState()
        {
            InitRefreshState();
            int ticket = Convert.ToInt32(Session[RefreshTicketCounter]) + 1;
            Session[RefreshTicketCounter] = ticket;
        }
        // **************************************************************

        // **************************************************************
        //NOTE: Maybe change this to only take a url - the user can add any parameters they want.
        /// <summary>
        /// Pops up a window, using the page at a given url.
        /// </summary>
        /// <param name="url">The url page to pop up.</param>
        /// <param name="Value">The value passing to the pop up</param>
        public void PopUpWindow(string Url, string Value)
        {
            PopUpUrl = Url;
            PopUpValue = Value;
        }
        // **************************************************************
        #endregion


        #region Private Members

            // **************************************************************
        /// <summary>
        /// Create the hidden field to store the current request ticket
        /// </summary>
            private void SaveRefreshState()
            {
                  int ticket = Convert.ToInt32(Session[RefreshTicketCounter]) + 1;
                  RegisterHiddenField(RefreshAction.CurrentRefreshTicketEntry, ticket.ToString());
            }
            // **************************************************************

            // **************************************************************
        /// <summary>
        /// Ensure that the ticket counter is initialized
        /// </summary>
            private void InitRefreshState()
            {
                  if (Session[RefreshTicketCounter] == null)
                        Session[RefreshTicketCounter] = 0;      
            }
            // **************************************************************

            // **************************************************************
            /// <summary>
            /// Handle the PreRender event
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void RefreshPage_PreRender(object sender, EventArgs e)
            {
                  SaveRefreshState();
                  AddSetFocusScript();
            AddTitleScript();
            // Only Render if we have info for the URL and a Value
            if(PopUpUrl != String.Empty && PopUpValue != String.Empty)
            {
                AddPopUpScript();
            }
            }
            // **************************************************************

            // **************************************************************
            /// <summary>
            /// Add any script code required for the Focus feature
            /// </summary>
            private void AddSetFocusScript()
            {
                  if (m_focusedControl == "")
                        return;

                  // Add the script to declare the function
                  // (Only one form in ASP.NET pages)
                  StringBuilder sb = new StringBuilder("");
                  sb.Append("\n\n<script language=javascript>\n");
                  sb.Append("function ");
                  sb.Append(FocusFunctionName);
                  sb.Append("(ctl) {\n\n");
                  sb.Append("  if (document.forms[0][ctl] != null)\n");
                  sb.Append("  {\n      document.forms[0][ctl].focus();\n");
            sb.Append("  }\n");
                  sb.Append("}\n");

                  // Add the script to call the function
                  sb.Append(FocusFunctionName);
                  sb.Append("('");
                  sb.Append(m_focusedControl);
                  sb.Append("');\n<");
                  sb.Append("/");   // break like this to avoid misunderstandings...
                  sb.Append("script>");

                  // Register the script (names are CASE-SENSITIVE)
                  if (!IsStartupScriptRegistered(FocusScriptName))
                        RegisterStartupScript(FocusScriptName, sb.ToString());
            }
            // **************************************************************


        // **************************************************************
        /// <summary>
        /// Register the Title startup Script for the form
        /// </summary>
        private void AddTitleScript()
        {
            StringBuilder sb = new StringBuilder("");
            sb.Append("\n<script language=javascript>\n");
            sb.Append("function ");
            sb.Append(TitleFunctionName);
            sb.Append("(title)\n{");
            sb.Append("\n    document.title = title;");
            sb.Append("\n");
            sb.Append("}\n\n");

            // Add the script to call the function
            sb.Append(TitleFunctionName);
            sb.Append("(");
            if(Title == String.Empty)
            {
                sb.Append("document.title");
            }
            else
            {
                sb.Append("'" + Title + "'");
            }            
            sb.Append(");\n<");
            sb.Append("/");            // break like this to avoid misunderstandings...
            sb.Append("script>");

            // Register the script (names are CASE-SENSITIVE)
            if (!IsStartupScriptRegistered(TitleScriptName))
                RegisterStartupScript(TitleScriptName, sb.ToString());
        }
        // **************************************************************


        // **************************************************************
        /// <summary>
        /// Dynamically builds a javascript function for a popup window
        /// </summary>
        private void AddPopUpScript()
        {
            StringBuilder sb = new StringBuilder("");
            sb.Append("\n<script language=javascript>\n");
            sb.Append("function ");
            sb.Append(PopUpFunctionName);
            sb.Append("()\n{");
            sb.Append("\n    win=window.open(\"" + PopUpUrl + PopUpValue);
            sb.Append("\",\"my_new_window\",\"toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=yes, width=575, height=450\")");
            sb.Append("\n\n");
            sb.Append("\n");
            sb.Append("}\n\n");

            // Add the script to call the function
            sb.Append(PopUpFunctionName);
            sb.Append("();\n<");
            sb.Append("/");   // break like this to avoid misunderstandings...
            sb.Append("script>");

            // Register the script (names are CASE-SENSITIVE)
            if (!IsStartupScriptRegistered(PopUpScriptName))
                RegisterStartupScript(PopUpScriptName, sb.ToString());
        }
        // **************************************************************

            #endregion


            #region Private Properties
            // ***********************************************************
            // Private properties
            private string m_focusedControl;
                private string m_PageTitle;
                private string m_PopUpUrl;
                private string m_PopUpValue;
            // ***********************************************************
            #endregion
      }
}




                           Using the Custom Class Snippet:
|-------------------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace PageTest
{
      /// <summary>
      /// Summary description for _default.
      /// </summary>
      public class _default : Msdn.Page  // <--- Notice Inheriting from our Custom Page
      {
                           protected System.Web.UI.WebControls.Label IsRefreshedLabel;
                           protected System.Web.UI.WebControls.Button TitleButton;
                           protected System.Web.UI.WebControls.Label Label2;
                           protected System.Web.UI.WebControls.Label Label3;
                           protected System.Web.UI.WebControls.TextBox TitleTextBox;
                           protected System.Web.UI.WebControls.TextBox PopUpTextBox;
                           protected System.Web.UI.WebControls.Label Label4;
                           protected System.Web.UI.WebControls.Button ChargeButton;
                           protected System.Web.UI.WebControls.Label ChargedLabel;
                           protected System.Web.UI.WebControls.Button PopUpButton;
                           protected System.Web.UI.WebControls.Button OperationButton;
                           protected System.Web.UI.WebControls.Label Label1;
   
            private void Page_Load(object sender, System.EventArgs e)
            {
                                      IsRefreshedLabel.Text = IsPageRefresh.ToString();
                                      this.Focus = "TitleTextBox";
                                      TrackRefreshState();
            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    
            this.TitleButton.Click += new System.EventHandler(this.TitleButton_Click);
            this.PopUpButton.Click += new System.EventHandler(this.PopUpButton_Click);
            this.ChargeButton.Click += new System.EventHandler(this.ChargeButton_Click);
            this.OperationButton.Click += new System.EventHandler(this.OperationButton_Click);
            this.Load += new System.EventHandler(this.Page_Load);

        }
            #endregion

        private void TitleButton_Click(object sender, System.EventArgs e)
        {
            Title = TitleTextBox.Text;
        }

        private void PopUpButton_Click(object sender, System.EventArgs e)
        {
            PopUpWindow("PopUp.aspx?Name=", PopUpTextBox.Text);
        }

        private void ChargeButton_Click(object sender, System.EventArgs e)
        {
            if(!IsPageRefresh)
            {
                ChargedLabel.Text = "Your Card has been charged!";
                ChargeButton.Enabled = false;
            }
            else
            {
                ChargeButton.Enabled = false;
                ChargedLabel.Text = "We Don't Want to Charge you twice!";
            }
            TrackRefreshState();
        }

        private void OperationButton_Click(object sender, System.EventArgs e)
        {
            Msdn.LengthyAction.Start("feedback.aspx", "work.aspx");
        }
   }
}

You can download the whole source here:
http://www.xamlcoder.com/downloads/EECustomPageTest.zip

Hope that helps!

 - Joe
0
 
LVL 3

Expert Comment

by:Realmrat
ID: 12651141
I'd gladly take the points.  Registering the javascript functions per page does work, but I think the idea of building upon a base page with base functionality it the best way to go.  =]

- Joe
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question