2

I'm trying to write a generic function that scours all the form-input controls inside a given parent so that I can repopulate the form's values at a later time.

I store each control's ID and VALUE in a cookie, and I repopulate the controls by using FindControl(ID) to locate the control before setting its VALUE.

All works fine, except in the case where I have multiple instances of a usercontrol, inside which there are child controls.

For example, a DateRange control defines two textboxes...

<asp:TextBox ID="txtDateFrom"  />
<asp:TextBox ID="txtDateTo"  />

Then in my form, if I have two DateRange controls...

<my:daterange id="DateRangeA" />
<my:daterange id="DateRangeB" />

...I now have 2 textboxes whose IDs are both txtDateFrom (and 2xtxtDateTo) thus I'm unable to either store both values in the cookie (as their IDs are not unique) nor retrieve the controls again using FindControl().

What I would like is something similar to FindControl(ID), but using the CLIENTID instead so that I can distinguish between child controls with the same ID inside different usercontrols.

I balk at the idea of having to manually store the complete path to all the controls (somehow), and then using FindControl(IDa).FindControl(IDb).FindControl(IDc)... (or whatever) to drill down to the child controls.

There must be a simpler way, right?

Or am I approaching this all wrong? Advice appreciated, thanks.

Bumpy
  • 1,290
  • 1
  • 22
  • 32

1 Answers1

2

Make your control implement the INamingContainer interface

According to the article :

Any control that implements this interface creates a new namespace in which all child control ID attributes are guaranteed to be unique within an entire application.

Also, check this article.

NomadTraveler
  • 1,086
  • 1
  • 12
  • 37
  • Hmm. Okay so I tried that, and while the IDs rendered to the HTML elements are now indeed unique, the ID accessible to the code-behind has not changed. Thanks for your advice. In the meantime, I have opted for a (hacky) workaround, and store EVERY control by `PARENTID+">"+ID` whether it needs it or not. Thus the following is enough to consistently locate any control I'm likely to use: `FindControl(PARENTID).FindControl(ID)` – Bumpy Oct 15 '13 at 01:46