使用VWD 2010 C#。default.aspx(.cs)。
要发生的事情:一个按钮用ID = "Day31"
更改标签的颜色。鉴于此示例是本月的第31天。按钮和标签位于" Main -Content"的表中。
protected void Red_Click(object sender, EventArgs e)
{
ContentPlaceHolder MainContent = Page.Master.FindControl("MainContent") as ContentPlaceHolder;
int theday;
theday = System.DateTime.Now.Day; // example the day is 31st
string str="Day"+theday;
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + str+ "');", true);
Label dayLabel = FindControl(str) as Label;
dayLabel.BackColor = System.Drawing.Color.Red; // this line error, "Null"
}
问题:为什么在这条代码线上有Null
错误消息?
它是无效的,因为该方法所在的容器中没有该特定ID值的控制,或者具有ID值不是Label
的控制类型。
如果您做Label dayLabel = MainContent.FindControl(str) as Label;
应该有效。