Focus On TextBox

  • Thread starter Thread starter A.M
  • Start date Start date
A

A.M

Hi,

Can I configure a TextBox to have focus and cursor on it when page gets
loaded?

Thanks,
Alan
 
A couple of approaces to use

The easiest is traditional HTML.
<body onload="javascript:document.myFormname.focusitemname.focus();">

where focusitemname is the textbox id

You could easily set this using registerstartupscript and setting the
focusitem dynamically
--
Regards

John Timney
Microsoft Regional Director
Microsoft MVP
 
Sure - you can inject some javascript into the page that does this for you:

Page.RegisterStartupScript("FocusedControl",
"<script language='javascript'>\r\ndocument.getElementById('" +
YourControl.Id + "').focus();\r\n</script>\r\n");


Better yet create a custom page class (or add it to your customized Page
class) by adding a FocusedControl property and then handling the insertion
automatically via the OnPreRender() event handler:

/// <summary>
/// Assigns focus to the specified control. Note the name must match the
exact
/// ID or container Id of the control in question.
/// Logic for this behavior is provided in OnPreRender()
/// </summary>
[Category("Behavior"),
Description("Set the focus of this form when it starts to the specified
control ID")]
public Control FocusedControl
{
get { return this.oFocusedControl; }
set { this.oFocusedControl = value; }
}
Control oFocusedControl = null;


/// <summary>
/// Overriden to handle the FocusedControl property.
/// </summary>
/// <param name="e"></param>
protected override void OnPreRender(EventArgs e)
{
if (this.FocusedControl != null)
this.RegisterStartupScript("FocusedControl","<script
language='javascript'>\r\ndocument.getElementById('" +
this.FocusedControl.ID + "').focus();\r\n</script>\r\n");

base.OnPreRender (e);
}


--

Rick Strahl
West Wind Technologies
http://www.west-wind.com/
http://www.west-wind.com/weblog/
 
Back
Top