Hi,
I'm trying to populate an asp:menu from a database on my master page and keep getting the error:
Object reference not set to an instance of an object

Here's my code on the master page:

<asp:Label runat="server" ID="errLabel" />
<asp:Menu ID="Categories" runat="server" CssClass="menu" EnableViewState="false" Orientation="Vertical" DataSourceID="categoryListSrc"></asp:Menu>
<asp:XmlDataSource ID="categoryListSrc" runat="server" TransformFile="~/TransformXSLT.xslt" XPath="MenuItems/MenuItem"></asp:XmlDataSource>

And here's the code behind:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim ds As New DataSet()
        Dim sqlStr As String
        Dim oMySqlConn As MySqlConnection = New MySqlConnection()
        oMySqlConn.ConnectionString = "User ID=myid;" & _
                                     "Password=mypass;" & _
                                     "Host=localhost;" & _
                                     "Port=3306;" & _
                                     "Database=mydb;" & _
                                     "Pooling=true;" & _
                                     "Min Pool Size=0;" & _
                                     "Max Pool Size=100;" & _
                                     "Connection Lifetime=0"

        sqlStr = "SELECT * FROM tbl_category"
        Dim dbcomm As New MySqlCommand(sqlStr, oMySqlConn)
        'dbcomm.Connection.Open()

        dbcomm = oMySqlConn.CreateCommand
        dbcomm.CommandText = sqlStr

        Dim da As New MySqlDataAdapter
        Try

            da.SelectCommand = dbcomm
            da.Fill(ds)
            da.Dispose()

            ds.DataSetName = "Menus"
            ds.Tables(0).TableName = "Categories"

            Dim parentColumn As DataColumn = ds.Tables("Categories").Columns("id")
            Dim childColumn As DataColumn = ds.Tables("Categories").Columns("parent")

            Dim relation As DataRelation
            relation = New DataRelation("ParentChild", parentColumn, childColumn)

            relation.Nested = True
            ds.Relations.Add(relation)

            categoryListSrc.Data = ds.GetXml()

        Catch ex As Exception
            errLabel.Text = ex.Message.ToString
        End Try

    End Sub

I think I'm missing something totally obvious but I can't see it.

i assume both front/back end code is on the master page right?

Back end code is in a code behind page.

Fixed it. There was an error in the data giving a circular reference and the

ds.GetXML

call was outputting the error message rather than the XML code resulting in the error as it tried to bind a non-existant datasource to the menu.

check for null ...Error makes a lot sense.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.