473,416 Members | 1,766 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,416 software developers and data experts.

asp.net setfocus after validation not working

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='javas cript'>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
Nov 18 '05 #1
4 9658
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("InitialFoc us", s.ToString());
}
}
catch
{
}
}

--
Regards,
Alvin Bruney
[ASP.NET MVP http://mvp.support.microsoft.com/default.aspx]
Got tidbits? Get it here... http://tinyurl.com/27cok
"Mad Scientist Jr" <us*************@yahoo.com> wrote in message
news:7a**************************@posting.google.c om...
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='javas cript'>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

Nov 18 '05 #2
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 (ra********@aol.com)
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 (sy******@hotmail.com)
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/de...s/tabindex.asp

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

Trevor

"Brian Watkins" <ra********@aol.com> wrote in message
news:O9**************@tk2msftngp13.phx.gbl...
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 (ra********@aol.com)
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 (ra********@aol.com)
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.
"Trevor Hartman" <sy******@hotmail.com> wrote in message
news:eg**************@TK2MSFTNGP12.phx.gbl...
Hey Brian,
Try out the HTML doc I included and view its source.

Regards,
Trevor
Nov 18 '05 #3
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.
Nov 18 '05 #4
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.txtJavascri pt.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?
Nov 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: amy | last post by:
I have a text box, after user input the value, a validate function trigered. if the value is invalid, alert display, and also set focus back to this control. The alert displays, but when the...
4
by: earwicker | last post by:
I recently deployed a web application which contains a user registration form with the usual fields: name, address, email, password, etc. Each of the TextBoxes uses a validation control to verify...
8
by: Shachar | last post by:
Hi All, I need to start a new process calc for example and when ever the user click on the button the application should setfocus to the calc application. I use this code but it is NOT...
2
by: dustbort | last post by:
I recently had a problem where my required field validator stopped working. But, the page still posted back and tried to insert a record into the database without performing server-side validation....
1
by: SDL | last post by:
The code below says error 2108 must save field before setfocus? All I want to do is check out the input field and if in error set the cursor back on it after the MsgBox displays. In this case I...
10
by: rockdc1981 | last post by:
Private Sub SupplierSKUCode_AfterUpdate() If Nz(DLookup("SupplierSKUCode", "tblProduct", "SupplierSKUCode='" & _ Me.SupplierSKUCode & "'"), "zzzz") <> "zzzz" Then MsgBox...
0
by: trint | last post by:
I have several GridViews that call a fuction, when clicked, called "getSelected". The very last thing I want getSelected to do is to SetFocus on a FormView (FormView1). Here is how I have this...
8
by: hawaiijeff | last post by:
I am writing an order receiving application in Access 2000. In this app you type in the tanker number the app looks that up in a table and should return just one row. The code below is showing how...
3
by: ckrows | last post by:
I have a main form with a button that makes a subform visible. I added a button in the form footer of the subform that is supposed to hide the subform. This does not work because the focus is on...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.