开发者

C# General Question about Master Page

I am trying to add a label the following way

public partial class _base : System.Web.UI.MasterPage
{
    protected void Page_Load(object send开发者_Go百科er, EventArgs e)
    {

        lblText.Text ="Hello";
    }
}

}

The problem is it is telling Object reference not set to an intance of an object. This is the code behind my MasterPage.cs.

  <asp:Label ID="lblText" runat="server" Text="Label"></asp:Label>

In master page


Where your code has

Label lblText;

you should put

Label lblText = new Label();

instead. This will make the error go away, because then an actual instance of the label control will be referenced by the lblText variable. But the label will not show up until you also add

 Controls.Add(lblText);

to your page load event.

Alternatively, you could add the label to your page as @amonteiro suggests. Then you could put it in a location that makes sense for the rest of your application.


You can't find lblText in your page because it's not part of the page's class. It's part of the master page's class. You have to find it in the master page like so:

Label lblText = (Label) Master.FindControl("lblText")};

Also, don't use a Label if a Literal will do the trick.

Edit: Just realized I might have read your question wrong. If you're trying to find it in the code behind for the Master page itself, then my answer does not apply.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜