How to Build a NavBar From a SQL Database

2010-08-28 10:49:18来源:西部e网作者:

I hope this will help many of you out there that might be getting a migraine over figuring this out. This is so that everyone can understand it, i recommend using OOP for code management.

Vince

Private Sub buildMenu()

        Dim strSelParent As String = "SELECT * from parentTable"
        Dim strSelChild As String = "SELECT * from childTable"

        Dim strConn As String = ConfigurationManager.ConnectionStrings("MySqlConnection").ToString
        Dim SqlConn As SqlConnection = New SqlConnection(strConn)
        Dim SqlCmd As SqlCommand = New SqlCommand(strSelParent, SqlConn)

        SqlConn.Open()

        Dim rd As SqlDataReader = SqlCmd.ExecuteReader()

        While rd.Read
     Dim newItem As ComponentArt.Web.UI.NavBarItem = New ComponentArt.Web.UI.NavBarItem()
     'Set the Parent Menu text
     newItem.Text = rd("MenuText")
     'Set the parent Menu Value
     newItem.Value = rd("ItemId")
     'Set the parent menu ID - this part is important as we will need it
     'to set the children items
     newItem.ID = rd("ItemId")
     'add the new item to the navbar
     Me.NavBar1.Items.Add(newItem)
        End While

        rd.Close()
        SqlConn.Close()

        SqlCmd = New SqlCommand(strSelChild, SqlConn)

        SqlConn.Open()

        rd = SqlCmd.ExecuteReader()

        Dim strParentID As String
        Dim strMenuText As String
        Dim strItemId As String

        While rd.Read
     Dim newItem As ComponentArt.Web.UI.NavBarItem = New ComponentArt.Web.UI.NavBarItem()

     'get the parentID of the child menu item
     strParentID = rd("ParentItemId")
     'get the child menu text
     strMenuText = rd("MenuText")
     'get the id of the child menu
     strItemId = rd("ItemId")

     'pass the above data into a new menu item
     newItem.Text = strMenuText
     newItem.Value = strItemId

     'use a try catch just in case
     Try
         'now find the parent item by it's id and add the child item 
         Me.NavBar1.FindItemById(strParentID).Items.Add(newItem)
     Catch
     End Try

        End While

        rd.Close()
        SqlConn.Clone()

    End Sub

 

关键词:ASP.NET

赞助商链接: