473,782 Members | 2,531 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Set Focus on PostBack

8 New Member
Well I wasn't to sure if post this on the javascript forum or here, but since is an error that probably I got because something related to my ASP.Net code I decided to posted here.

Ok my problem is that I need to set focus on a textbox everytime the page is loaded. Maybe you already thinking what I thought at first, that with a textbox.setFocu s() that will do it. Nop this is .Net Framework 1.1 and textbox.setFocu s() didn't exist back then. So I did the other simple thing add a javascript on body onload="documen t.getElementByI d(<%= txtPCode.Client ID %>).focus(). It works on page load but not in postback. I really have try a couple of other things like adding this function in the .vb
Expand|Select|Wrap|Line Numbers
  1.  
  2.         Private Sub SetFocus(ByVal ClientID As String)
  3.             Dim Script As New System.Text.StringBuilder
  4.             'Dim ClientID As String = FocusControl.ClientID
  5.             With Script
  6.                 .Append("<script language='javascript'>")
  7.                 .Append("document.getElementById('")
  8.                 .Append(ClientID)
  9.                 .Append("').focus();")
  10.                 .Append("</script>")
  11.             End With
  12.             RegisterStartupScript("setFocus", Script.ToString())
  13.         End Sub
  14.  
and calling it in from the Page_Load like this SetFocus(textbo x.ClientID).

Anyway nothing of this have work to set the focus of the textbox on the page post back.

Anyone have another idea?

Thanks,

Erick
Jul 20 '07
24 3924
Frinavale
9,735 Recognized Expert Moderator Expert
Why all this talk of hidden textboxes?
He knows the name of the textbox.
It's not hidden.
mynothiddentext box.focus()

(Assuming one uses the NAME property, otherwise you'll need the getElementById( ))
Hmm I had to read the question again.
Maybe this person's using an Ajax call to do a partial page update?
Jul 25 '07 #11
erickme
8 New Member
I'm tired of looking for the problem. I didn't create the code, it was the guy before me so maybe he have something that it's not allowing this to work. Here is the code if anyone can figured it out.

Expand|Select|Wrap|Line Numbers
  1. Imports System.Data.Odbc
  2.  
  3. Namespace ASPNET.StarterKit.Portal
  4.  
  5.     Public Class ProductLookUpPage
  6.         'Inherits System.Web.UI.Page
  7.         Inherits ASPNET.StarterKit.Portal.PortalPage
  8.         Protected WithEvents lnkReturn0 As System.Web.UI.WebControls.LinkButton
  9.         Protected WithEvents lnkReturn1 As System.Web.UI.WebControls.LinkButton
  10.  
  11.         Protected WithEvents phBanner As System.Web.UI.WebControls.PlaceHolder
  12.         Protected WithEvents lblTitle As System.Web.UI.WebControls.Label
  13.         Protected WithEvents cmdLocate As System.Web.UI.WebControls.Button
  14.         Protected WithEvents txtPCode As System.Web.UI.WebControls.TextBox
  15.         Protected WithEvents vsPCode As System.Web.UI.WebControls.ValidationSummary
  16.         Protected WithEvents rfvPCode As System.Web.UI.WebControls.RequiredFieldValidator
  17.         Protected WithEvents revPCode As System.Web.UI.WebControls.RegularExpressionValidator
  18.         Protected WithEvents cvPCode As System.Web.UI.WebControls.CustomValidator
  19.         Protected WithEvents dlProductNumbers As System.Web.UI.WebControls.DataList
  20.         Protected WithEvents lblPCodeValue As System.Web.UI.WebControls.Label
  21.         Protected WithEvents lblDescValue As System.Web.UI.WebControls.Label
  22.         Protected WithEvents lblSizeValue As System.Web.UI.WebControls.Label
  23.         Protected WithEvents lblWHHead As System.Web.UI.WebControls.Label
  24.         Protected WithEvents lblWHQty As System.Web.UI.WebControls.Label
  25.         Protected WithEvents lblStoreHead As System.Web.UI.WebControls.Label
  26.         Protected WithEvents lblStoreQty As System.Web.UI.WebControls.Label
  27.         Protected WithEvents btnPriceIt As System.Web.UI.HtmlControls.HtmlInputButton
  28.         Protected WithEvents spnContent As System.Web.UI.HtmlControls.HtmlGenericControl
  29.  
  30. #Region " Web Form Designer Generated Code "
  31.  
  32.         'This call is required by the Web Form Designer.
  33.         <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
  34.  
  35.         End Sub
  36.  
  37.         Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
  38.             'CODEGEN: This method call is required by the Web Form Designer
  39.             'Do not modify it using the code editor.
  40.             InitializeComponent()
  41.         End Sub
  42.  
  43. #End Region
  44.  
  45.         Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  46.             Trace.Warn("Default.aspx.vb", "Called Page_Load()")
  47.             'DO NOT remove this line
  48.             'This is what loads the banner into the top
  49.             phBanner.Controls.Add(Page.LoadControl("../../../DesktopPortalBanner.ascx"))
  50.  
  51.             '07/20/07
  52.             SetFocus(txtPCode.ClientID)
  53.  
  54.             'Counteract the DHTML onclick event assigned to the Look-Up Command Button
  55.             txtPCode.Attributes.Add("onfocus", "document.forms(0).cmdLookup.disabled = false;")
  56.  
  57.             ' 03/16/05 WNS Added PriceIt
  58.             btnPriceIt.Visible = False
  59.             Page.RegisterHiddenField("__EVENTTARGET", cmdLocate.ClientID)
  60.             If Page.IsPostBack = False Then
  61.                 '  Store URL Referrer to return to portal
  62.                 Try
  63.                     ViewState("UrlReferrer") = Request.UrlReferrer.ToString()
  64.                 Catch ex As Exception
  65.                     Dim clsApp As New CustomAppSettings
  66.                     ViewState("UrlReferrer") = clsApp.GetAppSetting("StoreTab_Url")
  67.                 End Try
  68.  
  69.                 Page.RegisterHiddenField("__EVENTTARGET", cmdLocate.ClientID)
  70.  
  71.                 If Request.Params("pcode") <> "" Then
  72.                     Dim clsProducts As New ABCProducts
  73.                     If clsProducts.IsValidPCode(Request.Params("pcode")) Then
  74.                         txtPCode.Text = Request.Params("pcode")
  75.                         LocateProduct()
  76.                     End If
  77.                 End If
  78.  
  79.             End If
  80.             RegisterStartupScript("SetFocus", ("<script>document.getElementById('txtPCode').focus();</script>"))
  81.  
  82.         End Sub
  83.  
  84.         'DO NOT remove this return procedure
  85.         Private Sub lnkReturn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkReturn0.Click, lnkReturn1.Click
  86.             'Return to Portal
  87.             Response.Redirect(CType(ViewState("UrlReferrer"), String))
  88.         End Sub
  89.  
  90.         Private Sub cmdLocate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLocate.Click
  91.             'A PCode has been entered and the submit button clicked
  92.  
  93.             'Query the SIRBALP by PCode and load into DataSet
  94.             If Page.IsValid Then
  95.                 LocateProduct()
  96.             End If
  97.  
  98.         End Sub
  99.  
  100.         Public Sub ValidatePCode(ByVal sender As Object, ByVal e As ServerValidateEventArgs)
  101.             Try
  102.                 Dim intTest As Integer = txtPCode.Text
  103.             Catch ex As Exception
  104.                 e.IsValid = False
  105.                 Exit Sub
  106.             End Try
  107.  
  108.             'July 11, 2007
  109.             'Validates PCODE against AS400 to see if is valid
  110.             Dim sqlCmd As String = "SELECT * FROM ABCPROD.INVMSTP WHERE (PCODE = " & txtPCode.Text & ") "
  111.             Dim conn As New OdbcConnection(System.Configuration.ConfigurationSettings.AppSettings("AS400"))
  112.             Dim cmd As New OdbcCommand(sqlCmd, conn)
  113.             conn.Open()
  114.             Dim AS400reader As OdbcDataReader = cmd.ExecuteReader
  115.  
  116.             AS400reader.Read()
  117.  
  118.             If AS400reader.HasRows Then
  119.                 e.IsValid = True
  120.             Else
  121.                 e.IsValid = False
  122.             End If
  123.         End Sub
  124.  
  125.         Private Sub LocateProduct()
  126.             txtPCode.Text.Trim()
  127.  
  128.             Dim sqlCmd As String = "SELECT STORE_NO, PCODE, END_QTY, S#STAT " & _
  129.                     "FROM ABCPROD.SIRBALP, ABCPROD.STRMSTP " & _
  130.                     "WHERE ((ABCPROD.SIRBALP.STORE_NO = ABCPROD.STRMSTP.STRNO) " & _
  131.                     "AND (S#STAT = 'A')) " & _
  132.                     "AND (PCODE = " & txtPCode.Text & ") " & _
  133.                     "AND (STORE_NO <> 10) " & _
  134.                     "AND (STORE_NO <> 11) " & _
  135.                     "AND (STORE_NO < 219) " & _
  136.                     "AND (END_QTY > 0) " & _
  137.                     "ORDER BY STORE_NO, PCODE, END_QTY"
  138.  
  139.             Dim conn As New OdbcConnection(System.Configuration.ConfigurationSettings.AppSettings("AS400"))
  140.             Dim cmd As New OdbcCommand(sqlCmd, conn)
  141.             cmd.CommandType = CommandType.Text
  142.             Dim da As New OdbcDataAdapter(cmd)
  143.             Dim ds As New DataSet
  144.             da.Fill(ds)
  145.  
  146.             cmd.CommandText = "SELECT PCODE, ASIZE, DESC, OHQTY " & _
  147.                 "FROM ABCPROD.INVMSTP " & _
  148.                 "WHERE (PCODE = " & txtPCode.Text & ") "
  149.             da.SelectCommand = cmd
  150.             da.Fill(ds, "Product")
  151.  
  152.             lblPCodeValue.Text = ds.Tables("Product").Rows(0).Item("PCODE")
  153.             lblDescValue.Text = ds.Tables("Product").Rows(0).Item("DESC")
  154.             lblSizeValue.Text = ds.Tables("Product").Rows(0).Item("ASIZE")
  155.             lblWHQty.Text = ds.Tables("Product").Rows(0).Item("OHQTY")
  156.  
  157.             lblWHHead.Visible = True
  158.             lblWHQty.Visible = True
  159.  
  160.             ' if the requestor is at a store PC, then...
  161.             Dim vlVisitor As New ABCNetDepartmentMenu(Request.ServerVariables("remote_addr"))
  162.             If vlVisitor.IsStore Then
  163.                 Dim cmdStore As New OdbcCommand("SELECT STORE_NO, PCODE, END_QTY " & _
  164.                     "FROM ABCPROD.SIRBALP " & _
  165.                     "WHERE STORE_NO = " & vlVisitor.StoreNumber & _
  166.                     " AND PCODE = " & txtPCode.Text, conn)
  167.                 Dim daStore As New OdbcDataAdapter(cmdStore)
  168.                 conn.Open()
  169.                 Dim dr As OdbcDataReader = cmdStore.ExecuteReader
  170.  
  171.                 lblStoreQty.Text = 0
  172.                 While dr.Read
  173.                     lblStoreQty.Text = dr.Item("END_QTY")
  174.                 End While
  175.  
  176.                 daStore.Dispose()
  177.                 cmdStore.Dispose()
  178.                 conn.Dispose()
  179.  
  180.                 lblStoreHead.Visible = True
  181.                 lblStoreQty.Visible = True
  182.             End If
  183.             vlVisitor.Dispose()
  184.  
  185.             dlProductNumbers.DataSource = ds.Tables(0)
  186.             dlProductNumbers.DataBind()
  187.  
  188.             ds.Dispose()
  189.             da.Dispose()
  190.             cmd.Dispose()
  191.             conn.Dispose()
  192.  
  193.             ' 03/16/05 WNS Added PriceIt
  194.             With btnPriceIt
  195.                 .Visible = True
  196.                 .Attributes.Add("onclick", "NewWindow('PriceIt.aspx?pcode=" & txtPCode.Text & "','PriceLookUp',350,350,0,'center');")
  197.             End With
  198.  
  199.             '6/29/07 Clear textbox
  200.             txtPCode.Text = ""
  201.             SetFocus(txtPCode.ClientID)
  202.         End Sub
  203.  
  204.         '07/20/07 This procedure sets focus to specific controls.
  205.         Private Sub SetFocus(ByVal ClientID As String)
  206.             Dim Script As New System.Text.StringBuilder
  207.             'Dim ClientID As String = FocusControl.ClientID
  208.             With Script
  209.                 .Append("<script language='javascript'>")
  210.                 .Append("document.getElementById('")
  211.                 .Append(ClientID)
  212.                 .Append("').focus();")
  213.                 .Append("</script>")
  214.             End With
  215.             RegisterStartupScript("setFocus", Script.ToString())
  216.         End Sub
  217. End Namespace
  218.  
Thanks
Jul 27 '07 #12
Frinavale
9,735 Recognized Expert Moderator Expert
I'm tired of looking for the problem. I didn't create the code, it was the guy before me so maybe he have something that it's not allowing this to work. Here is the code if anyone can figured it out.
I remember having a similar problem to you in the past.
From what I remember, the problem was that the RegisterStartup Script method puts the JavaScript code in the <Body> portion of the Html. In order for the body to call your JavaScript function during the page's onload event, the JavaScript must exist in the <head> section of your Html.

What I to solve this solution was to put my JavaScript into an external JavaScript file hard code the import into the <head> section of my Html.

You don't need to put the JavaScript into an external file, but I'm almost certain that the JavaScript has to be defined in the <head> section in order to make the JavaScript call during your page's onload event.

eg:
Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  4. <HTML>
  5.     <HEAD>
  6.         <title>My Page's Title</title>
  7.         <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
  8.         <meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
  9.         <meta content="VBScript" name="vs_defaultClientScript">
  10.         <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
  11.         <LINK href="Styles.css" type="text/css" rel="stylesheet">    
  12.            <script type="text/javascript">
  13.                onload = function()
  14.                { 
  15.                   document.getElementById('myTextbox').focus();
  16.                }
  17.            </script>
  18.  
  19.     </HEAD>
  20.  

Have you tried hard coding the JavaScript into the <head> section to see if this works?

-Frinny
Jul 27 '07 #13
erickme
8 New Member
I have tried that, don't work for me. This is how my script section on the page looks.

Expand|Select|Wrap|Line Numbers
  1.             <script language="javascript">
  2.  
  3.                 var win=null;
  4.  
  5.                 function NewWindow(mypage,myname,w,h,scroll,pos)
  6.                 {
  7.                     if(win!=null && win.open) win.close()
  8.  
  9.                     if(pos=="random")
  10.                     {
  11.                         LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;
  12.                         TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;
  13.                     }
  14.  
  15.                     if(pos=="center")
  16.                     {
  17.                         LeftPosition=(screen.width)?(screen.width-w)/2:100;
  18.                         TopPosition=(screen.height)?(screen.height-h)/2:100;
  19.                     }
  20.                     else if((pos!="center" && pos!="random") || pos==null)
  21.                     {
  22.                         LeftPosition=0;TopPosition=20;
  23.                     }
  24.  
  25.                     settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
  26.                     win=window.open(mypage,myname,settings);
  27.  
  28.                     if(win.focus)
  29.                     {
  30.                         win.focus();
  31.                     }
  32.                 }
  33.  
  34.                 function CloseNewWin()
  35.                 {
  36.                     if(win!=null && win.open) win.close();
  37.                 }
  38.  
  39.                 onload = function()
  40.                 {
  41.                     document.getElementById('txtPCode').focus();
  42.                 }
  43.             </script>
  44.  
Jul 27 '07 #14
Frinavale
9,735 Recognized Expert Moderator Expert
I have tried that, don't work for me. This is how my script section on the page looks.
Are you getting an JavaScript errors on the page at all?
Like an "object expected" error or the like?
Jul 27 '07 #15
Plater
7,872 Recognized Expert Expert
As much as I hate to admit it (:-P) if you run it in firefox with that DOM parser thing on you will see a lot more hidden errors.

Are you remembering to have your body tag's onload function call out to that javascript onload thing
Jul 27 '07 #16
Frinavale
9,735 Recognized Expert Moderator Expert
I'm going to ask one more small but vital question.

Are you using any use of Ajax in your html design?
Are you using the AjaxControlTool kit's UpdatePanel?
Jul 27 '07 #17
erickme
8 New Member
I just tried with firefox and it works, but not with Internet explorer. I didn't get any javascript error. I don't get it, whats wrong with IE (lol) then.

I'm not using AJAX in this application, this is an old application, it was develop long time before I started working here.
Jul 27 '07 #18
Frinavale
9,735 Recognized Expert Moderator Expert
I just tried with firefox and it works, but not with Internet explorer. I didn't get any javascript error. I don't get it, whats wrong with IE (lol) then.

I'm not using AJAX in this application, this is an old application, it was develop long time before I started working here.
Have you checked out w3c?
Have you seen their focus() method example?

I tried their example in IE and it works fine....
Maybe you might find then answer in w3c.
Jul 27 '07 #19
erickme
8 New Member
Have you checked out w3c?
Have you seen their focus() method example?

I tried their example in IE and it works fine....
Maybe you might find then answer in w3c.
It doesn't seem to work with a asp button, I got this error:
Compiler Error Message: BC30390: 'ASPNET.Starter Kit.Portal.Prod uctLookUpPage.P rivate Sub SetFocus(Client ID As String)' is not accessible in this context because it is 'Private'.
Jul 27 '07 #20

Sign in to post your reply or Sign up for a free account.

Similar topics

2
5192
by: Marco Liedekerken | last post by:
Hi, Is it possible to retrieve the control that had the focus when the page was posted back? Because the focus is lost when a postback occurs I want to manually set the focus to the control that previously had the focus (smartnavigation doesn't do the trick). Thanks, Marco
2
2435
by: Elliot M. Rodriguez | last post by:
Is it possible to change a control's focus at runtime? I'm sure you can.... I have a form with 2 textbox controls that cause postbacks. They are located in the middle of my form. When a postback occurs, no control has the focus. I would like it to be so that the control that causes the postback keeps the focus. Since I have 2 controls that potentally need to retain focus, using Javascript in this case is a PIA.
6
1388
by: Mike | last post by:
I have a few textbox controls that have autopostback so that when they loose focus they update a label control that shows the count of characters in their respective text control. This works fine, except that after the postback, the page is shown reset -- scrolled to the top and with no control having focus. Can I maintain scroll/focus w/o writing client-side scripting? thanks
3
1647
by: Dexter | last post by:
Hello All, I have a web control that when receive the focus, a postback is called, using getPostBackEventReference. But, when the PostBack is called, i want that the focus goes to the web control. Somebody know how to make this? Dexter
1
1180
by: psual | last post by:
Hi I have a page (1st page) with a button. this button opens a new page (2nd page) in full-screen mode. The problem is that the 2nd page is always loaded before the postback of the 1st page, so the 1st page takes back the focus instead of remaining behind the 2nd page. Even if the 2nd page takes time to render, the 1st page waits for its
5
2040
by: Finn Stampe Mikkelsen | last post by:
Hi How can i set a focus to a textbox in my codebehind page?? I have this WebForm, that takes information from a user and 2 buttons on the form. One that takes action on the entered information and one that resets the form... The second on, the reset button, i would like to set focus back to the first textbox on the form. I already have an onload in my body, which sets the
2
3882
by: Rey | last post by:
Howdy all. Using visual web developer (VB) on xp pro box. My problem with with a web form that on accessing the calendar control causes a postback that moves the cursor back to the txtFirstName field. Form uses the Page_LoadComplete in order to access the last employeeID # in a dataview which is populated by an sqlDataObject querying an SQL Server dbs.
0
1787
by: BizEd | last post by:
I have a textbox that fires an autopostback when filled in. The next field after the textbox is a RadioButtonList which I set focus to. The radiobutton list does have focus and activates when you hit the spacebar, but the little selection box does not appear around the first item like it does when you tab to a radiobutton list. So in essence, the user has no idea where they are on the screen. I've tried both the focus() method and...
8
6904
by: Mel | last post by:
I have several text boxes and drop-down lists in an AJAX Update Panel. All user inputs have the Postback property set to True. After I type something in the first input entry and press the "Tab" key how can I set the focus to the next box after the postback? Please help! Using Visual Studio 2005 Pro, Asp.net 2.0, vb.net, WinXP
0
9639
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10311
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10080
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9942
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6733
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5509
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2874
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.