Set focus to a control on Page_Load

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi all,

Can anyone tell me how to set focus to particular control on Page_Load() in
ASP.Net? I could not find any Control.Focus() method.

Thanks for any help!

Tedmond
 
Howdy,

-- BEGIN CODE --

public static void SetFocus(Control control)
{
System.Text.StringBuilder script = new System.Text.StringBuilder();

script.Append("\r\n<script language='JavaScript'>\r\n");
script.Append("<!--\r\n");
script.Append("function OnWindowLoad()\r\n");
script.Append("{\r\n");
script.Append("\tdocument.");

Control parent = control.Parent;

// get parent form id
while (!(parent is System.Web.UI.HtmlControls.HtmlForm))
parent = parent.Parent;

script.Append(parent.ClientID);
script.Append("['");
script.Append(control.UniqueID);
script.Append("'].focus();\r\n");
script.Append("}\r\n");
script.Append("window.onload = OnWindowLoad;\r\n");
script.Append("// -->\r\n");
script.Append("</script>");

control.Page.RegisterClientScriptBlock("SetFocusScript",
script.ToString());
}

-- END CODE --
 
If you're using 1.x, you have to build your own using Javascript. The Focus
method is available in 2.0.
 
Hi Tedmond,

Set the TabIndex of the control (Which needs focus) to 0, and set all
the remaining controls TabIndex to consequent numbers.

This worked for me.

Cheers,
Kris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top