Solved

Setting focus on a text box

Posted on 2004-10-20
23
873 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
Comment Utility
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
Comment Utility
I got the following error: 'System.Web.UI.WebControls.TextBox' does not contain a definition for 'Select'
0
 
LVL 3

Expert Comment

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

Just a sec...
0
 
LVL 3

Expert Comment

by:aacool
Comment Utility
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
Comment Utility
That's javascript, btw
0
 

Author Comment

by:RosanneParnell
Comment Utility
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
Comment Utility
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
Comment Utility
0
 
LVL 3

Expert Comment

by:aacool
Comment Utility
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
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 3

Expert Comment

by:Realmrat
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
in the cs file (codebehind)
I usually put it in my page.onload
0
 

Author Comment

by:RosanneParnell
Comment Utility
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
Comment Utility
Can you post your relevant functions?
0
 
LVL 3

Expert Comment

by:Realmrat
Comment Utility
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
Comment Utility
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
Comment Utility
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

771 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now