Search code examples
asp.netvb.net-2010vwdexpress

Setting Focus on a TextBox


I have a small ASP.net web app for sales, when the "Make New Sale" page loads, I want the TextBox for the Barcode to be in focus, so that the user doesn't have to navigate to it and click it then enter the Barcode, how can I do that?

PS: I am using Visual Web Developer 2010 and VB.net.


Solution

  • You can do this either in your code behind, or directly in JavaScript on your page. To do it in your code behind, just call the Focus() method on the control:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        TextBox1.Focus()
    End Sub
    

    To do it in JavaScript, create a function that selects the textbox and calls its .focus() method, and call the function in the page's onLoad event:

    function SetFocus() {
        var textbox = document.getElementById("<%= TextBox1.ClientID %>");
        if(textbox != null) {
            textbox.focus();
        }
    }