Finding user control in TemplateField of DetailsView

Khanzor picture Khanzor · May 19, 2009 · Viewed 7.3k times · Source

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.

Answer

mmx picture mmx · May 19, 2009

After DataBinding the control, you'd use:

dvDetailsView.Rows[0].Cells[0].FindControl("ucUserControl")

And make sure you are doing this only in Edit mode as the control only exists in EditItemTemplate.