how to set focus on textbox after post back in

I had this issue when i manually Post Back our application while searching and filtering a data in a Grid View  So i searched on the internet and finally i completed it with combination of several examples. These codes did not invented by me. But i combined these examples into one working example and all credits should goes to original developers or bloggers and stackoverflow website. This is how i Post Back the page while typing in a text box in with c# in our application. code similar to below.

<asp:TextBox runat="server" ID="txtAutoSearch" AutoPostBack="True" 
  ontextchanged="txtAutoSearch_TextChanged" CssClass="content"
  ClientIDMode="Static" OnKeyUp="onTextBoxChanging(this);">

and the onTextBoxChanging(this) method similar to

<script type="text/javascript">

    var tbPostBackTimeout = null;

    function onTextBoxChanging(sender) {

        tbPostBackTimeout = setTimeout(function () {
         }, 1000);

    function afterTimeout() {
        __doPostBack('<%=txtAutoSearch.UniqueID %>', "onkeyup");



here txtAutoSearch is the text box which cause the postback and on the c# section we can call java script function to focus end of txtAutoSearch text box.In the Page_Load section we can call this piece of code

if (Request.Params["__EVENTTARGET"] == txtAutoSearch.UniqueID && Request.Params["__EVENTARGUMENT"] == "onkeyup")

and finally focusToTextBox() method similar to

private void focusToTextBox()
            string str = "var input = $('#txtAutoSearch');";
            str += "var len = input.val().length;";
            str += "input[0].focus();";
            str += "input[0].setSelectionRange(len, len);";

            ScriptManager.RegisterStartupScript(Page, this.GetType(), "id", str, true);

One thought on “how to set focus on textbox after post back in

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s