Focus on the first control

  • Thread starter Thread starter Rafael A. M. Borges
  • Start date Start date
R

Rafael A. M. Borges

Hi,

How can I set the focus on the first control in the page? I tried
Page.Controls(0).Focus() but it didn't works. Does anyone knows it?
 
this sets focus to the field named 'ctlMyField'

ctlMyField.Page.RegisterClientScriptBlock("InitialFocus", "<SCRIPT
FOR='window' EVENT='onload' LANGUAGE='JScript'>document.all." + ctlMyField +
".focus();</SCRIPT>");
 
this sets focus to the field named 'ctlMyField'

ctlMyField.Page.RegisterClientScriptBlock("InitialFocus", "<SCRIPT
FOR='window' EVENT='onload' LANGUAGE='JScript'>document.all." + ctlMyField +
".focus();</SCRIPT>");

Ok, but I want to do this in a master page, to set the focus on the
first control in the pages that inherits it. So I need to discover
programatically the first control of the page.

Thanks for your help
 
It could be tricky if you know nothing about the controls on content pages.
You could try polling through the controls to find the one with minimum
value of the TabIndex property and call SetFocus on it. But you can't
guarantee the right order of TabIndex values. Polling the Controls
collection should be recursive. And what will you do if the first control is
just an html control and not a web control in the first place?

I would suggest introducing a property on the master page where content page
would set the id of the control that should get focus and the master page
would set focus based on this id.

--
Eliyahu Goldin,
Software Developer & Consultant
Microsoft MVP [ASP.NET]
http://msmvps.com/blogs/egoldin
http://usableasp.net
 
It could be tricky if you know nothing about the controls on content pages.
You could try polling through the controls to find the one with minimum
value of the TabIndex property and call SetFocus on it. But you can't
guarantee the right order of TabIndex values. Polling the Controls
collection should be recursive. And what will you do if the first control is
just an html control and not a web control in the first place?

I would suggest introducing a property on the master page where content page
would set the id of the control that should get focus and the master page
would set focus based on this id.

--

An alternative is to define an interface that content pages must
implement to benefit from the focus treatment - e.g

public interface FocusFirst
{
WebControl First {get; set;}
}

the master page then addresses the interface like this

FocusFirst f = Page as FocusFirst;
if (f != null)
f.First.Focus();
 
Back
Top