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

Last Reply one year ago By kalpesh

Posted one year ago

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 asp.net 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)
{
    txtSearch.focus();
}

 

You are viewing reply posted by: kalpesh one year ago.
Posted one year ago Modified on one year ago

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

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function setCursorPosition(element, pos) {
            var ctrl = document.getElementById(element);

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

C#

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);        
}   

VB.Net

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

Screenshot