Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Move Cursor to End of Textbox

Status
Not open for further replies.

Silo4

Programmer
Nov 7, 2002
17
GB
Hi,

I am using a button to insert a string into a textbox on my webform. I want the cursor position to be set to the end of the inserted text so the user can continue typing without having to manually reposition the cursor.

In a VB.NET windows form i'd use...

TextBox1.Text = "Hello World"
TextBox1.Focus()
TextBox1.SelectionStart = TextBox1.Text.Length

I can insert the text and focus back onto the textbox, but when the textbox recieves focus the cursor is reset to the start of the text.

Does anyone know how i can set the cursor to the end in ASP.NET?

Thanks
 
You will have to use a javascript function as it will need to be done on the client. Ask your question in the javascript forum as the question is more appropiate there.

--------------------------------------------------------------------------------------------------------------------------------------------

Need help finding an answer?

Try the search facility ( or read FAQ222-2244 on how to get better results.
 
It's taken a while but i've finally figured it out. I've built it into a VB.NET function for use in ASP.NET. Cut and paste below and simply call the function.

Silo4

Sub SetCaretPosToEnd(ByVal ctrl As Control)
Dim sb As New System.Text.StringBuilder("")
With sb
.Append("<script language='JavaScript'>")
.Append("function GetCaretPos ()")
.Append("{")
.Append("var MyControl = ")
.Append("document.")
.Append(ctrl.Parent.ID)
.Append("['")
.Append(ctrl.UniqueID)
.Append("'] ;")

.Append("if (MyControl.createTextRange)")
.Append("{")
.Append("var range = MyControl.createTextRange();")
.Append("range.collapse(false);")
.Append("range.select();")
.Append("}")
.Append("else if (control.setSelectionRange)")
.Append("{")
.Append("var range = MyControl.createTextRange();")
.Append("range.collapse(false);")
.Append("range.select();")
.Append("}")
.Append("}")
.Append("window.onload = SetCaretPosToEnd;")
.Append("</script")
.Append(">")
End With
ctrl.Page.RegisterClientScriptBlock("SetCaretPosToEnd", sb.ToString())
End Sub
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top