开发者

finding an HtmlGenericControl

   System.Web.UI.HtmlControls.HtmlGenericControl div = (System.Web.UI.HtmlControls.HtmlGenericControl)pnl.Controls[0].FindControl("divMessage");

i am trying to find divMessage somethign like the above but i am getting null...:

开发者_C百科

below is how my div resides.

 <mobile:Panel ID="pnl" Runat="server">
   <mobile:DeviceSpecific ID="device" runat="server">
            <ContentTemplate>
          <div id="divMessage" runat="server">test.....</div>
       </ContentTemplate>
          </mobile:DeviceSpecific>
 </mobile:Panel>


This should find the div you needed:

var div = (HtmlGenericControl)pnl.Controls[0].FindControl("divMessage");

I created a new page and tested through it:

<%@ Page Language="C#" Inherits="System.Web.UI.MobileControls.MobilePage" %>
<%@ Register TagPrefix="mobile"
    Namespace="System.Web.UI.MobileControls"
    Assembly="System.Web.Mobile" %>

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        var div = (HtmlGenericControl)pnl.Controls[0].FindControl("divMessage");
    }

</script>
<body>
    <mobile:form id="form1" runat="server">

    <mobile:panel id="pnl" runat="server">
        <mobile:DeviceSpecific ID="device" runat="server">
            <Choice>
                <ContentTemplate>
                    <div id="divMessage" runat="server">test.....</div>
                </ContentTemplate>
            </Choice>
        </mobile:DeviceSpecific>
    </mobile:panel>

    </mobile:form>
</body>
</html>

The div variable contains the control you need.


The easiest way to find the control is to do a recursive search, as your current method is probably failing due to the way the controls are nested.

/// <summary>
/// Recursive FindControl method, to search a control and all child
/// controls for a control with the specified ID.
/// </summary>
/// <returns>Control if found or null</returns>
public static Control FindControlRecursive(Control root, string id)
{
    if (id == string.Empty)
        return null;

    if (root.ID == id)
        return root;

    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null)
        {
            return t;
        }
    }
    return null;
}

You can then use this method in the following way:

HtmlGenericControl div = (HtmlGenericControl) FindControlRecursive(pnl, "divMessage");


I believe the problem is because the pnl control does not contain divMessage. You have to iterate down into the containing controls to find it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜