Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a server control work with asp:Label's AssociatedControlID property

Tags:

asp.net

label

When you set the AssociatedControlID property on a Label control, it renders a <label> HTML tag with its for attribute set to the target control's ClientID:

<label id="Label" for="TextBox">Dat TextBox</label>
<input id="TextBox" name="TextBox" type="text">

I've made a server control that has a TextBox inside it and I would like for the label to render its for attribute to my control's interior TextBox. My first thought was to point directly to my server control:

<asp:Label ID="AwesomeLabel" runat="server" AssociatedControlID="AwesomeControl">
    Check out my awesome control!</asp:Label>
<custom:MyControl ID="AwesomeControl" runat="Server" />

But that makes the for attribute point to the <span> that is rendered around the server control's contents:

<label id="AwesomeLabel" for="AwesomeControl">Check out my awesome control!</label>
<span id="AwesomeControl">
    <input name="AwesomeControl$ct123" type="text"></span>

It seems as though AssociatedControlID sets the for attribute by simply getting the target control's ClientID:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.label.associatedcontrolid.aspx

I don't want to go into the page's .aspx.cs to set this programmatically, because this server control is used frequently and I'd like its implementation to be as quick as possible.

Is there any other way to make Label tags render their for attributes to my server control's interior TextBox, either in the .aspx markup or from my server control's code?

like image 603
Calvin Fisher Avatar asked Dec 28 '25 16:12

Calvin Fisher


2 Answers

If your usercontrol has the ID AwesomeControl and the textbox inside the usercontrol has the ID AwesomeTextbox, you have to set the AssociatedControlID to this: AwesomeControl:AwesomeTextbox.

<asp:Label ID="AwesomeLabel" runat="server" AssociatedControlID="AwesomeControl:AwesomeTextbox">
Check out my awesome control!</asp:Label>
<custom:MyControl ID="AwesomeControl" runat="Server" />
like image 173
Kairo Avatar answered Dec 31 '25 17:12

Kairo


Currently your span is the element which possesses the id you are point to and your input doesn't have any ID.

Give your input element an ID and change the label so it points to that ID.

<asp:Label ID="AwesomeLabel" runat="server" AssociatedControlID="txtAwesomeControl">
    Check out my awesome control!</asp:Label>

<span id="AwesomeControl">
    <input id="txtAwesomeControl" name="AwesomeControl$ct123" type="text" />
</span>
like image 22
Adauto Avatar answered Dec 31 '25 19:12

Adauto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!