We generally need to select contents of a TextBox while using validation for it. For this, if we are using javascript validation then we may code like-
document.getElementById("<%=TextBox1.ClientID%>").select();
But, we need some other way, when we want this on some other events in code behind. For instance, let consider we have a TextBox in a page, whose purpose is to display the next receipt no. by adding 1 to the previous receipt no.,but it can be changed if user wants to do so and that’s why when cursor comes to this TextBox through any event , contents of this TextBox will be highlighted so that user can have an idea that it can be changed or, need to be changed. To achieve this we will follow below steps.
Step-1: We have to define a javascript function in the .aspx page inside script tag-
function selectText() { document.getElementById("<%=TextBox1.ClientID %>").select(); }
Step-2: On page load event, we will set the attribute of the TextBox to-
TextBox1.Attributes.Add("onfocus","selectText();");
You are a very smart individual!
For anyone who wants the element to be selected only once (on the postback) use this:
TextBox1.Attributes.Add(“onfocus”, “this.select(); this.onfocus = null;”);