Select contents of a TextBox on focus in ASP.Net (Code behind)

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-


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-


2 thoughts on “Select contents of a TextBox on focus in ASP.Net (Code behind)

  1. For anyone who wants the element to be selected only once (on the postback) use this:
    TextBox1.Attributes.Add(“onfocus”, “; this.onfocus = null;”);

Leave a Reply to joe Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s