Set Focus to last Character Index of TextBox on PostBack using C#, Vb.Net and JavaScript

Last Reply on Feb 16, 2018 02:42 AM By kalpesh

Posted on Feb 15, 2018 11:05 PM

when my page is postback i use .focus() on textbox but cursor go on first index position in textbox i want to set it on last index position automatically in C#.

when my page postback through txtSearch_TextChanges method my cursor automatically go on first index but i want to set it on last index using this code.

protected void txtSearch_TextChanged(object sender, EventArgs e)


Posted on Feb 16, 2018 02:42 AM Modified on on Feb 16, 2018 02:47 AM

Refer the below sample code and implement it as per your code logic.


<html xmlns="">
<head runat="server">
    <script type="text/javascript">
        function setCursorPosition(element, pos) {
            var ctrl = document.getElementById(element);

            if (ctrl.setSelectionRange) {
                ctrl.setSelectionRange(pos, pos);
            else if (ctrl.createTextRange) {
                var range = ctrl.createTextRange();
                range.moveEnd('character', pos);
                range.moveStart('character', pos);
    <form id="form1" runat="server">
        Search&nbsp;<asp:TextBox ID="txtSearch" runat="server" OnTextChanged="txtSearch_TextChanged"
            AutoPostBack="true"></asp:TextBox><br />
        <asp:Button Text="Submit" runat="server" />


protected void txtSearch_TextChanged(object sender, EventArgs e)
    var position = txtSearch.Text.IndexOf(txtSearch.Text) + txtSearch.Text.Length + 1;
    var script = String.Format("setCursorPosition('{0}',{1});", txtSearch.ClientID, position);
    ClientScript.RegisterStartupScript(GetType(), "CursorScript", script, true);        


Protected Sub txtSearch_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
    Dim position = txtSearch.Text.IndexOf(txtSearch.Text) + txtSearch.Text.Length + 1
    Dim script = String.Format("setCursorPosition('{0}',{1});", txtSearch.ClientID, position)
    ClientScript.RegisterStartupScript([GetType](), "CursorScript", script, True)
End Sub