How to associate a Label with a TextBox or other Form control in ASP.NET

The next code shows how you can attach an asp:Label control with the asp:TextBox. In this case when the user clicks the Label the application will focus on the TextBox.

 

TestAssociate.aspx

<%@ Page Language=”vb” AutoEventWireup=”false” CodeBehind=”TestAssociate.aspx.vb” Inherits=”TextChange.TestAssociate” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head runat=”server”>

<title>Associate a Label with a TextBox</title>

</head>

<body>

<form id=”form1″ runat=”server”>

<div>

<asp:Label ID=”LabelEMail” runat=”server” Text=”E-Mail: ” AssociatedControlID=”TextEMail”></asp:Label>

<asp:TextBox ID=”TextEMail” runat=”server”></asp:TextBox>

</div>

</form>

</body>

</html>

You can associate the Label to the TextBox control by specifying the Label property AssociateControlID to the TextBox’s ID. Clicking on the Label control focuses the TextBox.