Setting focus on control in the code-behind VB.NET


Can anyone tell me if you see anything wrong with this code? I'm trying to set focus on txt_job textbox when a button is clicked.


1        Private Sub SetFocusScript(ByVal strTextBox As String)
3            Dim sb As New System.Text.StringBuilder()
5            sb.Append("<script language='javascript'>")
7            sb.Append("document.frmView." & strTextBox & ".focus();")
9            sb.Append("</script>")
11           ' register the script
13           If Not ClientScript.IsStartupScriptRegistered("myBoxSelect") Then
15               ClientScript.RegisterStartupScript(Me.GetType, "myBoxSelect", sb.ToString())
17           End If
19       End Sub

Thanks in advance,
Ravina Brar
Software Developer
University Of Alberta
The man who smiles when things go wrong has thought of someone to blame it on.
- Robert Bloch
5/7/2008 3:38:50 PM 13973 articles. 1 followers. Follow

5 Replies

Similar Articles

[PageSpeed] 58

Are you passing the TextBox clientID to the method of just the ID? You will need to pass this to get the javascript to work:


Don't forget to click "Mark as Answer" on the post(s) that helped you.

NHibernate with Problem-Design-Solution sample application
Scott blog

5/7/2008 3:51:37 PM

Look this approach:

Private Sub SetFocusScript(ByVal ClientID As String) 
    If Not ClientScript.IsStartupScriptRegistered("SetFocus") Then
        Dim s As String = "<script language=|javascript| type=|text/javascript|>" + "document.form1." + ClientID + ".focus();" + "</script>"
        ClientScript.RegisterStartupScript(Me.[GetType](), "SetFocus", s.Replace("|"C, """"C))
    End If
End Sub

' samples
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)
End Sub

Notes. Original source:
    private void SetFocusScript(string ClientID)
    {// by Harvey Triana
        if (!ClientScript.IsStartupScriptRegistered("SetFocus"))
            string s = "<script language=|javascript| type=|text/javascript|>"
                        + "document.form1." + ClientID + ".focus();"
                        + "</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "SetFocus", s.Replace('|', '"'));
    // samples
    protected void Button1_Click(object sender, EventArgs e)
    protected void Button2_Click(object sender, EventArgs e)

convert tool:

Harvey Triana
5/7/2008 4:36:49 PM
You can use ScriptManager.SetFocus() to do that a bit easier.

Encosia - ASP.NET, AJAX, and more.

Latest article: Using complex types to make calling services less… complex
5/7/2008 6:57:08 PM

Yes. It is a better option.

Harvey Triana
5/7/2008 7:24:57 PM

Thank You.
That is a easier way.

Appreciate all the responses.

Ravina Brar
Software Developer
University Of Alberta
The man who smiles when things go wrong has thought of someone to blame it on.
- Robert Bloch
5/7/2008 8:27:21 PM

Similar Artilces:

Setting width for .net controls in code(.aspx) page using function call in code behind..
Hi,  Currently I am trying to set the width of the Table as follows. <asp:Table width="<%=GetWidth()%>" >   and code behind protected Unit GetWidth() { return Unit.Percentage(50); }     It's not working. I know that it works if I set the width complete on some page event(like page_load) of code behind....   Is there a way to maintain the same syntax like calling code behind function in design page...i.e. calling function of .aspx.cs in .aspx page and assign the width as shown above.   Thanks and regards, Giridhar...

How to convert C#.Net code to VB.Net code ???...
HI, i was searching something new, then i suddenly find some tips to convert C#.Net code to VB.Net but i did not do well. i am puttint its url here plz tell me how to convert C#.Net code to VB.Net. Jasim...Please remember to click “Mark as Answer” on the post that helps youJasim AkhtarNew Delhi ( INDIA ) It would be better if you write the problem you having, while converting from C# to VB.NET. You cannot completely rely on online converters. ThanksMark post(s) as "Answer" that helped youElectronic ScrewWebsite||Bl...

Translate code to code
Hi I can usually do the translation myself, but this time I am a bit stumped  Let us consider to rewrite Urls (more than 16000 links) using a table. Save original url and rewritten url in a table. Now add a class file in App_Code folder. class UrlRewriteModule : IHttpModule{    public void Dispose()    {        // Nothing to dispose    }    public void Init(HttpApplication context)    {        context.BeginRequest += new EventHandler(context...

use VB.NET and C#.NET code in the same C#.NET project
All-- Here is a sample that is "off the beaten path", (at least for me). Is it possible, in an ASP.NET application, using the code-behind page building technique, to have both pages written in VB.NET and pages written C#.NET?At there is a sample that shows that, (contrary to popular belief), it IS possible to mix ASP.NET pages built with C#.NET with ASP.NET pages built with VB.NET in the same VS.NET 2003 project. Note that this is just a "fun" sample to see if it can be done and I do not recommend this practice as a "standard" way of develo... data controls not found in code behind?
I am trying to follow along some of the very basic tutorials by scott gu but using  When I try and databind from my code behind I get an intellisense error that the control cannot be found?  Doesn't matter if it is a listview a repeater or whatever. Here is my code behind:1 Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 2 Repeater1.datasource = ViewData("Categories") 3 Repeater1.databind() 4 End SubHere is my front end aspx: 1 <%@ Page Language="vb" AutoEve...

Sending SMS using or using or
Hi  My requirement is I hav one csv file with these fields id,mobilenum,messgae,status.intiallu staus is 0. once i read the all fileds and take that mobile number.using tat mobile number  i need to send sms .after sending sms i shuld change status as 1 How to send sms thru coding (please dont provide any links.if it is provide also please give working links becox i checked codeproject .i didnt get any nice link. and also provide the how to update the status field im csv file   Thank ssandhya   To send SMS, you need some third party SMS providers. if you consul...

Accessing Form Controls via code behind (VB.NET)
Hi,I hope someone can help provide some light on this problem I'm having. I have searched the forums and found another post on ASP.NET that references how to access controls on a form using for example:Dim lstResourceServers As WebControl = frmASP.FindControl("lstResourceServers")This will indeed give me access to the listbox control on the form but I can't access the properties and methods specific to the listbox control class such as Items, SelectedIndex, etc. which to me is rather pointless.If I place a listbox or any other component on my page I can directly acc...

how to call javascript from code behind (not due to control event)
Hi, I have a question about calling javascript from code behind. I have a database application that after a click of a button it will return a dataset. Depending on the returned dataset, I would like to run a certain client-side script, e.g. msgbox etc. How can I do that? I've searched the forum it seems like most of the examples were related to a control event such as button_click. An example of the general code would be: sub button_click() 'Get a dataset (datareader) cmd.Connection=cn cmd.CommandText=sql dim dr as oledbdataread...

Accessing user control in repeater from code behind in would be great
Hello i have a repeater which has a user control hard coded inside of it. I would like to be able to access the properties of the user control from code behind, but am having no luck "seeing" the usercontrol. If someone could help me out, that would be great.  Here is the repeater....<asp:Repeater ID="Repeater0" runat="server"> <HeaderTemplate> </HeaderTemplate> <ItemTemplate> <uc1:billToInfo ID="billToInfo1" billTo="<%#Container.dataItem %>" runat="server" /> </It...

Setting Control Properties Using VB.Net Code in the aspx Source Files.
How would I set a property of a .net Control file in the source file to a Variable or a Function name in the code behind file.  I've seen various examples of this, but I have never understood the syntax. Is there a good tutorial on this? I would like to understand code like Text='<%# Bind("DepartmentDesc") %>' />. Hi, rspiet:I would like to understand code like Text='<%# Bind("DepartmentDesc") %>' />. Based on my experience, we could use Data Bind  Expressions like "<%%>" to bind the data sou...

How to migrate code from to
Hi all,If anybody knows information on migration of VB.Net application to i.e Any tools available, best practices, methodology for estimation. etc.   RegardsHelen    Hey, Take a look at this topic some of these sites can be of help to you.  Arnold you can do it by page by page just copy and paste ur page in the following link and convert ur to c# gotcha!!YasserSpica.www.spica.aewww.bncnetwork.netPlease remember to mark as answers i...

How to change code to C#.Net ?...
Hi, Earlier i had a class  that i got it from this Forum, it in and i am trying it to convert it in but i am unable to covert properly to work. the functionality of this class is to convert number value to words. i am putting both of code and please rectify it.Public Class NumberToWords Dim Character As String Public Function ConvertNumber(ByVal A As Double) As String On Error Resume Next Dim MM Dim IM ConvertNumber = "" MM = Microsoft.VisualBasic.Len(A) IM = Microsoft.VisualBasic.Left(A, Mic...

Migrate code from to
Hello friends, I had created a web site using visual studio 2005. web site was created using the language vb i.e. Now as per the clint requirement I have to migrate all the code in C#. So the question is that is there any tool or any inbuild utility in Visual Stuidio so that we can migrate the site from to Or we have to do it mannually i.e. by changing each and every line of code mannually? Kindly suggest me. Thanks & Regards Girish NehteThanks & RegardsGirish NehteIf This post helps you to solve your problem please mark this as an answer. Hi, at the mome...

converting to from offered me some sample code when I signed up with them the only problem is the sample code is in but my page that they type all of their credit card into is <code><%@ Import Namespace="System.Net" %> <%@ Import Namespace="System.IO" %> <script language="C#" runat="server"> void Page_Load(Object Src, EventArgs E) { myPage.Text = readHtmlPage(""); } private String readHtmlPage(string url) { ...

Web resources about - Setting focus on control in the code-behind VB.NET -

Looking at the code behind our three uses of Apache Hadoop - Facebook
Facebook Engineering hat eine Notiz mit dem Titel Looking at the code behind our three uses of Apache Hadoop geschrieben. Du kannst den vollständigen ...

How Heartbleed Works: The Code Behind the Internet's Security Nightmare
By now you've surely heard of Heartbleed, the hole in the internet's security that exposed countless encrypted transactions to any attacker who ...

Anatomy of an interactive: a look at the code behind our Second Screen
... and Paralympics coming to town, this presented the perfect opportunity to try it on. Being mainly responsible for the client-side code, I'll ...

How Heartbleed Works: The Code Behind the Internet's Security Nightmare
By now you've surely heard of Heartbleed, the hole in the internet's security that exposed countless encrypted transactions to any attacker who ...

Resources last updated: 2/4/2016 4:54:58 AM