.NET User/server Control With Custom List Items
I'm attempting to create a simple menu user control just as outlined here.
The attached code results in an "Object reference not set to an instance of an object" error, but I can't figure out why. Any thoughts?
<%@ Master Language="VB" CodeFile="MySite.master.vb" Inherits="MySite" %>
<%@ Register src="Controls/Menu.ascx" tagname="Menu" tagprefix="my" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>MySite</title>
<link href="Styles/MySite.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder id="headContent" runat="server">
</asp:ContentPlaceHolder>
</head>
<body id="masterBody" runat="server">
<form id="form1" runat="server">
<my:Menu ID="Menu1" runat="server">
<MenuItems>
<my:MenuItem Text="Test" NavigateUrl="~/Default.aspx" />
</MenuItems>
</my:Menu>
</form>
</body>
</html>
Partial Class Controls_Menu
Inherits System.Web.UI.UserControl
Private m_Items As List(Of MenuItem) = Nothing
<PersistenceMode(PersistenceMode.InnerProperty)> _
Public Property MenuItems() As List(Of MenuItem)
Get
Return m_Items
End Get
Set(ByV开发者_StackOverflowal value As List(Of MenuItem))
m_Items = value
End Set
End Property
End Class
Public Class MenuItem
Private m_Text As String
Public Property Text() As String
Get
Return m_Text
End Get
Set(ByVal value As String)
End Set
End Property
Private m_NavigateUrl As String
Public Property NavigateUrl() As String
Get
Return m_NavigateUrl
End Get
Set(ByVal value As String)
m_NavigateUrl = value
End Set
End Property
End Class
The problem is that here:
<MenuItems>
<my:MenuItem Text="Test" NavigateUrl="~/Default.aspx" />
</MenuItems>
ASP.net is trying to Add to your MenuItems list, it does this by calling
MenuItems.Add(...)
However, since m_Items is equal to Nothing, this gives you the error. To fix this replace
Private m_Items As List(Of MenuItem) = Nothing
With
Private m_Items As List(Of MenuItem) = New List(Of MenuItem)()
精彩评论