I would like to share a little trick which allows to fix NullReferenceException (object reference not set to an instance of an object) when you add new server control on your application _layouts page or user control in control templates folder. So you add e.g. new <asp:Textbox ID=”txtEmail” runat=”server” /> control and add appropriate protected Textbox txtEmail into codebehind class of your page. But when you try to access properties of this new control you may get NullReferenceException in runtime:
1: // here NullReferenceException can occur
2: this.txtEmail.Text = "foo@example.com";
This problem is rare but happens. In order to fix it you can at first try to clear "Temporary ASP.NET Files" folder. But sometimes it doesn’t help. Ofcourse you can use workaround like this:
1: var txtEmail = (TextBox)FindControl("txtEmail");
2: txtEmail.Text = "foo@example.com";
but it looks not effective and looks not elegant (especially if all other controls are working successfully). So if you encountered with such situation you can try to add the following line on top of you aspx page of ascx control:
1: <%@ Register TagPrefix="asp" Namespace="System.Web.UI.WebControls" Assembly="System.Web,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" %>
and copy file into 12 hive. Sometime it helps. After that (if NullReferenceException disappeared) you can remove this line from page – it should still work after that. Thanks hodzanassredin which told about this workaround.
No comments:
Post a Comment