明輝手游網(wǎng)中心:是一個(gè)免費(fèi)提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺(tái)!

使用遞歸從數(shù)據(jù)庫(kù)讀取數(shù)據(jù)來(lái)動(dòng)態(tài)創(chuàng)建菜單

[摘要]表結(jié)構(gòu)與內(nèi)容 MenBh MenText Bhparent 0001 文件 0002 編輯 0005 打開(kāi) 0001 0006 ...
表結(jié)構(gòu)與內(nèi)容

MenBh            MenText     Bhparent

 

0001             文件         

0002             編輯         

0005             打開(kāi)          0001

0006             新建          0001

0011             access數(shù)據(jù)庫(kù)  0006

0012             VFPDbf      0006

0013             剪切          0002

0014             復(fù)制          0002

0015            完全復(fù)制       0014

 

 

    

Private m As New MainMenu()

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim conn As New SqlConnection("server=localhost;uid=sa;pwd=;database=jiang")

        Dim cmd As New SqlCommand("select * from a_menu ", conn)

        Dim ds As New DataSet()

        Dim sqldpr As New SqlDataAdapter(cmd)

        sqldpr.Fill(ds, "menu")

        Me.DataGrid1.DataSource = ds.Tables("menu")

        '創(chuàng)建關(guān)系

        Dim dr As New DataRelation("self_menu", ds.Tables("menu").Columns("MenBh"), ds.Tables("menu").Columns("Bhparent"))

        ds.Relations.Add(dr)

        Dim r1 As DataRow

        '查找最高的菜單級(jí)別,也就是Bhparent列為空的行

        For Each r1 In ds.Tables("menu").Rows

            If r1.IsNull("Bhparent") Then

                addmenuitem(r1, Nothing)

            End If

        Next

        Me.Menu = m '指定主窗體菜單

    End Sub

    '遞歸函數(shù)

    Private Sub addmenuitem(ByVal r As DataRow, ByVal item As MenuItem)

        Dim mi As MenuItem

        '如果是最外層菜單,要直接添加

        If item Is Nothing Then

            mi = m.MenuItems.Add(r.Item("MenText"))

        Else '如果是下級(jí)菜單要在菜單項(xiàng)的上級(jí)添加

            mi = item.MenuItems.Add(r.Item("MenText"))

        End If

        Dim r2 As DataRow

        For Each r2 In r.GetChildRows("self_menu")

            addmenuitem(r2, mi)

        Next

    End Sub

'--------------------------------------------------------一種方法的改進(jìn)

/////////////////////////////////////////////////////////////////////////////////////

繼承自menuitem的類(lèi)

/////////////////////////////////////////////////////////////////////////////////////

Public Class mymenuitem

Inherits System.Windows.Forms.MenuItem

 

Public Sub New(ByVal s As String, ByVal tag As String)

        MyBase.New()

        Me.Text = s

        m_tag = tag

    End Sub

    Private m_tag As String

    Public Property tag() As String

        Get

            Return m_tag

        End Get

        Set(ByVal Value As String)

            m_tag = Value

        End Set

End Property

  End class


[1] [2]  下一頁(yè)