data-bindinggridviewnaming-containers

Custom Naming Container for ASP.NET GridView?


I'm looking for information on how to implement a custom naming container for the items in a GridView. My issue is that I have a GridView with a cell for each day of the week, and each cell will contain the same or similar controls. For the controls that are the same, it'd be nice to name them all the same, such as "lblPersonName".

However, if you do that, you cannot use FindControl(), because it will complain that there are controls with duplicate IDs within the row. The root of the issue is that the naming container for controls in a GridView is not the cell of the table (DataControlFieldCell or whatever), but it is the GridViewRow.

I don't know if there's a way to do this, but it'd be nice to be able to swap out the default naming container so that the cell does become the naming container, and then I could just have the same control names.

Granted, the ASPX for this starts to get a little big - I'm starting to wish I had started the project off in ASP.NET MVC....

In any case, I'm open to other alternatives as far as how to implement a GridView with controls like this. At this point it might be cleaner just to use a plain old table and add the controls dynamically...

For clarification: - Each column is defined with an ItemTemplate, and the controls live within the ItemTemplate. - The only way to get it to work right now is to have "lblPersonNameOne", "lblPersonNameTwo", etc.


Solution

  • Actually, it seems like it might be pretty easy...what I'm experimenting with right now is I created a customer server control that inherits from asp:Panel, but it implements INamingContainer. When you implement that, it automatically inserts the ID of the control into the Unique ID stream of child controls.

    So then, you can add the controls from each Template with the same IDs (either dynamically or declaratively), and they will get their own ID. Then you just have to use FindControl on the cell itself, not on the row, and it will find the control with the searched for ID + the unique ID add-on.

    The solution above works, but it might be just as easy and cleaner to just put all the same-named controls inside a plain old ascx user control, which I believe implements INamingContainer. Then, you can use it as you normally would. The only downside to using a user control is that you can't databind as easily to datasources on the parent page, and things like that. Still possible of course going through the parent, but not as declarative.