views:

901

answers:

2

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.

+1  A: 

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.

Mehrdad Afshari
Still can't find this control, although I have another that I can find (it's just an `<asp:TextBox>` control.
Khanzor
Are you sure your details view is in edit mode, and you are doing it after DataBinding? I just tested and this worked. Check `CurrentMode` property to see if you are really in edit mode.
Mehrdad Afshari
No row should exist before data binding. Let alone child controls.
Mehrdad Afshari
+1  A: 

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 a dvSituation.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.

Khanzor