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-

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();");
About these ads

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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s