I have a page with textboxes and buttons. When the page loads, often times, focus is in one of the textboxes and I don't want this to happen. However, I don't want to use something like setfocus in the page load event because then when buttons are clicked the page will jump. How do prevent the textboxes or any controls for that matter of getting focus on page load?
strange. by default, the page will not focus on any form input unless you set focus on it.
I think you have to cancel all focus by Setfocus on page.
protected void Page_Load(object sender, EventArgs e)
{
// make sure its not a postback
if (!IsPostBack)
{
// your code
InitForm();
InitBlaBlaBla();
SetFocusOnThis();
SetFocusOnThat();
// cancel all focus
Focus();
}
else
{
// this is a postback,
// set focus on control which make post back
Control control = null;
if (!string.IsNullOrEmpty(Page.Request.Params[postEventSourceID]))
{
control = Page.FindControl(Page.Request.Params[postEventSourceID]);
}
else
{
// if postEventSourceID is null, its a button
// find it by iterating all controls
foreach (string ctl in Page.Request.Form)
{
Control c = Page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
// finally
control.Focus();
}
}
basically what I want to do is when the page loads as the result of redirecting from another page, don't set the focus in any textboxes, just load the page normally, but if the page loads as a result of clicking a control on the page, keep the focus on/near that control.
To accomplish this you have to test for post back. If you detect the page has been posted back, you can set focus to the control, as you intend to. Otherwise, the page is not beeing posted back (GET), so you can avoid the focus on the control.
As far as I know, by default, ASP.NET Webforms don't set the focus on any of textbox
es. Are you sure you don't have some code-behind method setting the focus on the textbox
?
It turns out that freetextbox controls exhibit this behavior on IE7 and IE6. It is a bug they are investigating.