0

I'm trying to populate an ASP Menu with ASP MenuItems dynamically from the code behind, but am getting an object reference is not set to an instance of an object exception.

This is what my ASP looks like:

<asp:Menu ID="HeaderMenu" runat="server">
    <Items>
    </Items>
</asp:Menu>

And this is what my code behind looks like:

protected void Page_Load(object sender, EventArgs e)
{
    PopulateMenu();
}

protected void PopulateMenu()
{
    HeaderMenu.Items.Add(new MenuItem 
    {
        Text = "Register Now!",
        NavigateUrl = "~/Pages/Register.aspx"
    });
}

It's throwing the exception on calling Add, but I can't figure out why.

EDIT: PopulateMenu() is being called on page load

शेखर
  • 16,910
  • 12
  • 52
  • 105
Alucir
  • 1
  • 3

1 Answers1

0

try this

<asp:Menu ID="HeaderMenu" runat="server">
    <Items>
    </Items>
</asp:Menu>


protected void Page_Load(object sender, EventArgs e)
{
    PopulateMenu();
}

protected void PopulateMenu()
{
    HeaderMenu.Items.Add(new MenuItem 
    {
        "Register Now!",
        "","", 
        "~/Pages/Register.aspx"
    });
}
Sagar Hirapara
  • 1,617
  • 13
  • 24