异常详细信息: System.Web.HttpException: 控件包含代码块(即 <% ... %> ),因此无法修改控件集合。
<%= DateTime.Now.ToString("HH-mm")%>
</asp:Panel>
Label lb=new Label();
lb.Text = "当前时间";
p_Time.Controls.Add(lb);
以上代码执行的时候,将会产生该错误。由于p_Time控件中包含了代码块(即<% ... %>),无法修改控件集合,所以当执行语句p_Time.Controls.Add(lb)时会产生错误。
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript">
function showTime()
{
var now = new Date();
var lbTime = document.getElementById('<%= this.lb_Time.ClientID %>');
lbTime.innerHTML = now.getHours() + ":" + now.getMinutes();
}
</script>
</head>
<body>
<asp:Label ID="lb_Time" runat="server" Text="lb_Time"></asp:Label>
<input id="btn_Show" type="button" value="button" οnclick="return showTime()" />
</body>
</html>
解决方案如下:
-
1、把javascript放到body中
2、声明自定义控件来代替包含了代码块(即<% ... %>)
-
控件代码:
public class ControlInfoWriter : Control
{
private string writerControlID;
private string writerProperty;
public string WriterControlID
{
get { return writerControlID; }
set { writerControlID = value; }
}
public string WriterProperty
{
get { return writerProperty; }
set { writerProperty = value; }
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
object writerControl = this.Parent.FindControl(writerControlID);//查找要输出的控件
Type t = writerControl.GetType();//获取控件的类型
PropertyInfo pi = t.GetProperty(writerProperty);//获取要输出的属性
string value = pi.GetValue(writerControl, null).ToString();//得到控件的属性值
writer.Write(value);
base.Render(writer);
}
}
head中的javascript修改如下:
<script type="text/javascript">
function showTime()
{
var now = new Date();
var lbTime = document.getElementById('<CustomControl:ControlInfoWriter ID="controlInfoWriter" WriterControlID="lb_Time" WriterProperty="ClientID" runat="server" />');
lbTime.innerHTML = now.getHours() + ":" + now.getMinutes();
}
</script>
注:页面代码中要注册控件CustomControl:ControlInfoWriter