动态添加菜单

数据库结构
menu_id         menu_text     menu_parid
010                1                     Null
010-001         11                   010
010-002         12                   010
010-002-001  121                 010-002
010-002-002  122                 010-002
020                 2                     Null
020-001          21                   020
020-002          22                   020

 

sql脚步:

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[testtable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[testtable]
GO

CREATE TABLE [dbo].[testtable] (
 [menu_id] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
 [menu_text] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
 [menu_parid] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO

 

根据以上数据库表内容动态加载菜单,源码如下:

Public Class Form1 Private ConnString As String = "Data Source=(local);Initial Catalog=tempdb;Integrated Security=True" Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim theMenu As New ContextMenuStrip Dim sql As String = "select * from testtable where menu_parid is null " Dim rst As DataSet = ExecuteSQL(sql) If rst IsNot Nothing Then Dim dt As DataTable = rst.Tables(0) For i As Integer = 0 To dt.Rows.Count - 1 Dim MenuItem As New ToolStripMenuItem(dt.Rows(i).Item("menu_text").ToString) Call GetMenuItem(MenuItem, dt.Rows(i).Item("menu_id").ToString) theMenu.Items.Add(MenuItem) Next End If Me.ContextMenuStrip = theMenu End Sub Private Function GetMenuItem(ByVal item As ToolStripMenuItem, ByVal id As String) As String Dim sql As String = "select * from testtable where menu_parid='" + id + "'" Dim rst As DataSet = ExecuteSQL(sql) If rst IsNot Nothing Then Dim dt As DataTable = rst.Tables(0) For i As Integer = 0 To dt.Rows.Count - 1 Dim MenuItem As New ToolStripMenuItem(dt.Rows(i).Item("menu_text").ToString) Call GetMenuItem(MenuItem, dt.Rows(i).Item("menu_id")) item.DropDownItems.Add(MenuItem) Next End If End Function Public Function ExecuteSQL(ByVal strSQL As String) As DataSet Dim sqlConnection As New System.Data.SqlClient.SqlConnection(Me.ConnString) Dim rst As System.Data.DataSet = Nothing Try sqlConnection.Open() rst = New System.Data.DataSet Dim adpt As New System.Data.SqlClient.SqlDataAdapter(strSQL, sqlConnection) adpt.Fill(rst) : adpt.Dispose() Return rst Catch ex As Exception Throw New Exception(ex.Message) Finally sqlConnection.Close() End Try Return rst End Function End Class

你可能感兴趣的:(exception,String,null,Integer,menu,dataset)