Finding user control in TemplateField of DetailsView

一个人想着一个人 提交于 2019-11-30 09:30:18

问题


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:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/881416/finding-user-control-in-templatefield-of-detailsview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!