asp.net setfocus after validation not working

M

Mad Scientist Jr

i am trying to set focus to a specific control depending on the
outcome of a validator control and it is not working.

none of these methods are working to setfocus:

1. RegisterStartupScript("sf","<scriptlanguage='javascript'>document.form.MyControlID.focus();</script>");

2. Andy Smith's FirstFocus control from
http://www.metabuilders.com/tools/FirstFocus.aspx

on my onchange event of field #1, based on the isvalid property of the
field #1 validators, i want to set focus either back to field #1 if it
is invalid, or to the next field #2 if it is valid. either way, it
always sets focus back to field #1 no matter what, so the user has to
press Tab twice to get to the next control, which is inconsistent with
all the other controls on the screen:

note the field names are generic Text1 and Text2 for simplicity

any help would be appreciated

Private Sub Text1_TextChanged(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles Text1.TextChanged

'run validation event
RequiredFieldValidator_Text1.Validate()
RegularExpressionValidator_Text1.Validate()

If (RequiredFieldValidator_Text1.IsValid and
RegularExpressionValidator_Text1.IsValid) then
' RECALCULATE SOME FIELDS
Call ReCalculateFields()
End If

' SET FOCUS ON NEXT CONTROL IF VALID, ELSE STAY IN SAME
CONTROL

Dim FirstFocus1 As MetaBuilders.WebControls.FirstFocus
FirstFocus1 = New MetaBuilders.WebControls.FirstFocus
FirstFocus1.Enabled = True

If RequiredFieldValidator_Text1.IsValid And
RegularExpressionValidator_Text1.IsValid Then ' goto next control

'this didn't work:
'Page.RegisterClientScriptBlock("SetFocus", "<script>
language='javascript'>document.body.onload = function(){
document.form.Text2.focus();}</script>")

'this didn't work either
'RegisterStartupScript("SetFocus1",
"<scriptlanguage='javascript'>document.form.Text2.focus();</script>")

'this also doesn't work:
FirstFocus1.ControlToFocus = Text2.UniqueID

Else

'this didn't work:
'Page.RegisterClientScriptBlock("SetFocus", "<script>
language='javascript'>document.body.onload = function(){
document.form.Text1.focus();}</script>")

'this didn't work either:
'RegisterStartupScript("SetFocus1",
"<scriptlanguage='javascript'>document.form.Text1.focus();</script>")

'this also doesn't work:
FirstFocus1.ControlToFocus = Text1.UniqueID

End If
 
A

Alvin Bruney [MVP]

ok but this should work if you call
SetInitialFocus(TextBox1);

/// <param name="control">Control to set the InitialFocus on.</param>
public static void SetInitialFocus(System.Web.UI.Control control)
{
try
{
if (control.Page == null)
{
throw new ArgumentException(
"The Control must be added to a Page before you can set the
IntialFocus to it.");
}

if (control.Page.Request.Browser.JavaScript == true)
{
//safe guard for IE blow up
control.Page.SmartNavigation = false;

// Create JavaScript
System.Text.StringBuilder s = new System.Text.StringBuilder();
s.Append("\n<SCRIPT LANGUAGE='JavaScript'>\n");
s.Append("<!--\n");
s.Append("function SetInitialFocus()\n");
s.Append("{\n");
s.Append(" document.all.");

// Find the Form
System.Web.UI.Control p = control.Parent;
while (!(p is System.Web.UI.HtmlControls.HtmlForm))
p = p.Parent;

s.Append(p.ClientID);
s.Append("['");
s.Append(control.UniqueID);
// Set Focus on the selected item of a RadioButtonList
System.Web.UI.WebControls.TextBox rbl = control as
System.Web.UI.WebControls.TextBox;
s.Append("'].focus();\n ");
s.Append("}\n");

if (control.Page.SmartNavigation)
s.Append("window.setTimeout(SetInitialFocus, 500);\n");
else
s.Append("window.onload = SetInitialFocus;\n");

s.Append("// -->\n");
s.Append("</SCRIPT>");

// Register Client Script
control.Page.RegisterClientScriptBlock("InitialFocus", s.ToString());
}
}
catch
{
}
}
 
M

Mad Scientist Jr

The problem is I want to be able to control the next control from
codebehind, based on operations done from codebehind (SQL calls etc).
The codebehind reads some server side textboxes and does some
calculations and checks some things on the back end, and depending on
the outcome, would setfocus to the appropriate control. It should be
able to do this by either registerclientside or startup script, or by
setting a hidden textbox with the setfocus javascript that the page
onload javascript calls with a javascript eval function. Basically, I
need some way for codebehind to indicate which control to go to to the
clientside javascript.

-------------------

This person had a similar problem, and had to do everything
javascript:

From: Brian Watkins ([email protected])
Subject: Focus help needed


View this article only
Newsgroups: microsoft.public.dotnet.framework.aspnet
Date: 2003-06-19 13:22:16 PST


Hello,

When I type data into a text box and then exit it (via any means, tab,
click) i want to know how to make the focus go to the next logical
control.
I can set the focus to the correct text box initially by executing (In
Page_load or Page_Init) a subroutine called setfocus that contains the
document.getElementById javascript code. When I try to call the
setfocus
routine from the textchanged event of my text boxes it doesn't work.
It
appears that this has to do with the AutoPostBack being set for my
textboxes. For whatever reason ASP.net is determined to place the
focus
where it thinks the focus should be (usually the textbox that fired
the
autopostback) after a postback. Call me crazy but I would like to
have
full control over the focus in my app. It is unusable until I resolve
this.
Has anyone else had this problem or am I doing something foolish?
Any work
arounds known? Thanks for your help in advance!
Message 2 in thread
From: Trevor Hartman ([email protected])
Subject: Re: Focus help needed


View this article only
Newsgroups: microsoft.public.dotnet.framework.aspnet
Date: 2003-06-19 13:40:10 PST


You should be able to control the focus of any items on the page, but
your
coding should be client side, not server side asp.net. You might also
want
to checkout the TABINDEX Attribute here:
http://msdn.microsoft.com/library/d...uthor/dhtml/reference/properties/tabindex.asp

If you need more help with setting up some client side javascript let
me
know.

Trevor

Brian Watkins said:
Hello,

When I type data into a text box and then exit it (via any means, tab,
click) i want to know how to make the focus go to the next logical control.
I can set the focus to the correct text box initially by executing (In
Page_load or Page_Init) a subroutine called setfocus that contains the
document.getElementById javascript code. When I try to call the setfocus
routine from the textchanged event of my text boxes it doesn't work. It
appears that this has to do with the AutoPostBack being set for my
textboxes. For whatever reason ASP.net is determined to place the focus
where it thinks the focus should be (usually the textbox that fired the
autopostback) after a postback. Call me crazy but I would like to have
full control over the focus in my app. It is unusable until I resolve this.
Has anyone else had this problem or am I doing something foolish? Any work
arounds known? Thanks for your help in advance!
Message 3 in thread
From: Brian Watkins ([email protected])
Subject: Re: Focus help needed


View this article only
Newsgroups: microsoft.public.dotnet.framework.aspnet
Date: 2003-06-20 05:47:55 PST


Thanks Trevor!

A Jscript example would be very helpful to me.

Say I have an .aspx page with two textboxes (txt1, txt2) and a label
(lblTotal).

When a number is typed into either of the text boxes I want to update
lblTotal with txt1.text + txt2.text and then shift the focus to the
other
textbox.

If you could show me a little client side jscript to do this I would
be
grateful. Thanks
Message 4 in thread
From: Brian Watkins ([email protected])
Subject: Re: Focus help needed


View this article only
Newsgroups: microsoft.public.dotnet.framework.aspnet
Date: 2003-06-23 07:18:13 PST


Thanks!

I guess that you have to manage focus with javascript. I wish that
Microsoft would have documented this better. I've wasted about a week
trying to manage the focus with server side code. All the advantages
of events and autopostbacks are dwindled considerably now. Not mush
use for asp.net may just go back to asp for server code and jscript
for
client side.
Hey Brian,
Try out the HTML doc I included and view its source.

Regards,
Trevor
 
M

Mad Scientist Jr

I found a simple workaround. By adding an onchange attribute to a
control, you can force focus to the next control:

dim sJS as string
sJS = "document.Form1." & DropDownList1.UniqueID & ".focus();"
Text1.Attributes.Add("onchange", sJS)

This works if the next control you want to set focus to is a
dropdownlist, but for some reason, if the next control is a textbox:

dim sJS as string
sJS = "document.Form1." & Text2.UniqueID & ".focus();"
Text1.Attributes.Add("onchange", sJS)

when the focus gets set to it you can't type in it. However if you
tab, it tabs correctly to the next control after that. So it is sort
of receiving the focus but not really. When it renders the page .NET
adds a "dopostback" to the onchange javascript. When you view source,
the onchange property is:

onchange="javascript:document.Form1.Text2.focus();__doPostBack('Text1','')"

I think the doPostBack is interfering with the focus command. If I
could somehow specify for my focus command to appear in the onchange
property AFTER the doPostBack, it might work. If anyone can tell me
how to do this, it would be most appreciated.
 
M

Mad Scientist Jr

Ultimately, the answer to the whole thing ended up being: turn off
Smart Navigation. It was screwing everything up. I couldn't set the
values of server side controls from javascript, among other things.
The values would stay the same they were when the form first
initilaized. When I turned off smart navigation, these problems went
away.

To force focus to a particular control, I found this worked:

In the HTML body:

<body onload="javascript:eval(document.Form1.txtJavascript.value);">

In control's Autopostback event:

Private Sub Text1_TextChanged(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Text1.TextChanged
'(your code here)
'...
txtJavascript.Value = "document.Form1." & Text2.UniqueID &
".focus();"
End Sub ' Text1_TextChanged


Note: I haven't tried registerClientsideScript (or is it
registerStartupScript? I forget at the moment). They didn't work when
I had smartnavigation on but might with it off. Is this preferable to
the above method?
 

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

Members online

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top