I have a textbox in an asp.net web page. In case of postback, I need to set focus on last char in this texbox. how can I do this using c# without using anything like jQueries.. Thanks
Asked
Active
Viewed 1,777 times
2 Answers
4
Here is a variation of the solution proposed in Use JavaScript to place cursor at end of text in text input element:
void btnPostBack_Click(object sender, EventArgs e)
{
txtFocus.Attributes["onfocus"] = "var value = this.value; this.value = ''; this.value = value; onfocus = null;";
txtFocus.Focus();
}

Community
- 1
- 1

ConnorsFan
- 70,558
- 13
- 122
- 146
-
It didnt work. focus is going back to the textbox but the cursor is not at last character in this textbox – Dani Apr 22 '16 at 12:15
-
You must be testing on Firefox. I had tested on IE and Chrome. I will see if there is a way to do the same in Firefox. – ConnorsFan Apr 22 '16 at 12:21
-
Exactly!!! im working on firefox, i tried it on chrome and it worked but unfortunatly i need it on firefox – Dani Apr 22 '16 at 12:24
-
I made a correction to the code. You can try again. – ConnorsFan Apr 22 '16 at 12:25
-
You're welcome! I made an additional correction, to avoid some misbehavior when using the form after the postback. Setting the focus to another control and putting it back in the TextBox always pushed the caret at the end, which was not correct. – ConnorsFan Apr 22 '16 at 12:31
0
Your code like below :
asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" ontextchanged="TextBox1_TextChanged" TabIndex="1"> asp:TextBox ID="TextBox2" runat="server" AutoPostBack="True" ontextchanged="TextBox2_TextChanged" TabIndex="2">
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Session["event_controle"] = ((TextBox)sender);
}
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
Session["event_controle"] = ((TextBox)sender);
}
protected void Page_PreRender(object sender, EventArgs e)
{
try
{
if (Session["event_controle"] != null)
{
TextBox controle =(TextBox) Session["event_controle"];
controle.Focus();
}
}
catch ()
{
}
}

Mahesh Bhosale
- 112
- 11