0

使用 VWD 2010 C#。默认.aspx(.cs)。
会发生什么:一个按钮用 改变标签的颜色ID = "Day31"。鉴于此示例是一个月的第 31 天。按钮和标签位于“MainContent”内的表格内。

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这行代码会出现错误信息?

4

2 回答 2

0

它是 null 或者是因为在该方法所在的容器中没有具有该特定 ID 值的控件,或者具有该 ID 值的控件不是 a Label,而是某种其他类型。

于 2012-11-07T19:53:03.460 回答
0

如果你这样做Label dayLabel = MainContent.FindControl(str) as Label;,它应该工作。

于 2012-11-07T20:03:27.830 回答