Search code examples
c#asp.net.netdetailsviewfindcontrol

Finding user control in TemplateField of DetailsView


I have a DetailsView that I'm posting back - and inside of that is a UserControl. I'm having some difficulty located it in the postback data.

As an example:

<asp:DetailsView ID="dvDetailsView" runat="Server" AutoGenerateRows="false">
<Fields>
  <asp:TemplateField>
    <ItemTemplate>
      Some text here
    </ItemTemplate>
    <EditItemTemplate>
      <uc:UserControl ID="ucUserControl" runat="server" />
    </EditItemTemplate>
    <InsertItemTemplate>
      <uc:UserControl ID="ucUserControl" runat="server" />
    </InsertItemTemplate>
  </asp:TemplateField>
</Fields>
</asp:DetailsView>

When I postback, I would assume I would do something like this:

MyUserControlType ucUserControl = dvDetailsView.FindControl("ucUserControl") as MyUserControlType;

But this finds nothing. In fact, I can't even find this baby by walking around in QuickWatch...

What do I need to do to find this thing??

EDIT: It turns out my usercontrol id was being changed - but why? I do have the same ID on both the insert and edit templates, but commenting that out made no difference.


Solution

  • As it turns out, the user control name was changed - my usercontrol, labelled as "ucUserControl" had it's name changed to a generic name - 'ctl01'.

    So, doing advSituation.Rows[0].Cells[0].FindControl("ctl01") found the control.

    To find this ID, I just had a look at the HTML element being rendered, and checked the parent from the id, e.g. 'ctl00_MainContent_dvDetailsView_ctl01_lblLabel', where lblLabel appeared on ucUserControl.

    The rows column is a 0 based index of the number of fields, and the cells index will be 1 if you have a headertemplate specified.

    EDIT: OMG! Someone (it really wasn't me, I swear) had hidden the ID property on the control class!

    public partial class UserControl : BaseControl
    {
      public int Id;
    }
    

    This meant that when ASP.Net was generating the id, it couldn't, and just assigned a generic Id ('ctl01' in this case) to the control, rather than the actual name.

    Wow.