System.Web.UI.HtmlControls.HtmlGenericControl div = (System.Web.UI.HtmlControls.HtmlGenericControl)pnl.Controls[0].FindControl("divMessage");
我正在尝试找到类似上面的divMessage
,但我得到了空......:
<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>
答案 0 :(得分:6)
这应该找到您需要的div
:
var div = (HtmlGenericControl)pnl.Controls[0].FindControl("divMessage");
我创建了一个新页面并通过它进行了测试:
<%@ 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>
div
变量包含您需要的控件。
答案 1 :(得分:3)
找到控件的最简单方法是进行递归搜索,因为当前方法可能由于嵌套控件的方式而失败。
/// <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;
}
然后您可以通过以下方式使用此方法:
HtmlGenericControl div = (HtmlGenericControl) FindControlRecursive(pnl, "divMessage");
答案 2 :(得分:0)
我认为问题是因为pnl控件不包含divMessage。您必须迭代到包含控件才能找到它。