views:

370

answers:

2

Hi there.

I'm making a forms framework for a project, and have found that when trying to programmatically set the AssociatedControlID property of the asp:Label to its associated TextBox, I have to call ClientID to get ID to populate (not be null).

While debugging, this use of the intermediate window shows the issue:

_inputTextBox.ID
null
_inputTextBox.ClientID
"ctl00_MainContent_ctl01"
_inputTextBox.ID
"ctl01"

(Value is present 2nd time ID is called)

I'm setting *_inputLabel.AssociatedControlID = inputTextBox.ID in an overridden CreateChildControls(), and have tried in RenderContents() of my WebControl.

I've tried loading ClientID into a unused temp variable first, and it works, eg:

var x = _inputTextBox.ClientID;
_inputLabel.AssociatedControlID = _inputTextBox.ID;

Gives: (correct)

<label for="ctl00_MainContent_ctl01">Name of customer</label>
<input type="text" id="ctl00_MainContent_ctl01" name="ctl00$MainContent$ctl01"/>

Instead of: (incorrect)

<span>Name of customer</span>
<input type="text" id="ctl00_MainContent_ctl01" name="ctl00$MainContent$ctl01"/>

My question is - Why do I have to perform this hack? Is there a better way for ID to be reliably populated?

Thanks.

+1  A: 

The ID of dynamically created controls is null unless explicitly defined until the RenderControl method is called.

CptSkippy
+1  A: 

The best thing to do is set the id on the control yourself. If you don't one will automatically be generated when the controls protected EnsureID method is called.
This method is automatically called at various times including, but not limited to, when the getter for ClientID is accessed.
You should also be aware that if you are dynamically manipulating controls then it is possible that the dynamically generated ids could vary based on the order that you add the controls to the page.
Also, even if you aren't dynamically creating the controls the dynamically generated id can vary if you force the id generation (by accessing ClientID) in a different order.

drs9222