ASP:Hyperlink with dynamic url value from C# – “Object reference not set to an instance of an object”

Another gotcha found today.

I’ve created my ASP:Hyperlink field in the aspx page, with runat=”server” (oh yes, that one ain’t catching me out anymore).

In the C# code behind file, I set the URL to be one thing or another, depending on some other logic. It’s MyHyperlink.NavigateUrl = “blah.aspx”.

I run the thing, and I get “Object reference not set to an instance of an object”. Dammit!

Have I forgotten how to instantiate the field properly? It’s not in a grid view, or anything fancy like that.

A random Google result gave me the answer, phew! .NET3.5 and above requires the Hyperlink to have its NavigateUrl property set to something when created. So on the page I set it to “#”  on creation and then set it dynamically as necessary.

Another one not to forget!