使用数据库绑定菜单控件






3.92/5 (6投票s)
将菜单控件与类别和子类别列表绑定
图 1
图 2
引言
在本文中,我将展示如何将菜单控件与数据库绑定。假设您需要显示不同的类别及其子类别。当我们点击类别/子类别(见图 1)以查看类别/子类别的详细信息(见图 2)时,这段代码将会很有用。这段代码在选择子类别时,可以防止回发到服务器。
Using the Code
数据库详情
表名 - Category
表名 - SubCategory
有两个表(Category
,SubCategory
)相互关联。
下面是名为 BindMenu
的方法,它在页面加载期间绑定菜单控件。
- 创建连接字符串以建立与数据库的连接
Dim connectionString As String = WebConfigurationManager.ConnectionStrings_ ("DatabaseConnectionString1").ConnectionString Dim con As New SqlConnection(connectionString)
- 为两个表创建两个
DataAdapter
Dim dadCategories As New SqlDataAdapter("SELECT CatId,CatName FROM Category order by CatName", con) Dim dadSubCat As New SqlDataAdapter("SELECT SubCatId,CatId,SubCatName FROM SubCategory order by SubCatName", con)
- 创建一个
DataSet
并用两个表填充dataset
Dim dsCat As New DataSet() Using con con.Open() dadCategories.Fill(dsCat, "Category") dadSubCat.Fill(dsCat, "SubCategory") End Using
- 关联两个表并将关系命名为
Children
dsCat.Relations.Add("Children", dsCat.Tables("Category").Columns("CatId"), dsCat.Tables("SubCategory").Columns("CatId"))
- 循环遍历每个类别的数据及其相关子类别的数据。在每个循环中,我们创建菜单项并将其与菜单控件关联。
For Each categoryRow As DataRow In dsCat.Tables("Category").Rows Dim mNode As New MenuItem(CType(categoryRow("CatName"), String), "", "", "~/DetailView.aspx?CatID=" + CType(categoryRow("CatId"), String), "_parent") Menu1.Items.Add(mNode) Dim subCatRows() As DataRow = categoryRow.GetChildRows("Children") For Each row As DataRow In subCatRows Dim subCatName As String = CType(row("SubCatName"), String) Dim subCatItems As New MenuItem(subCatName, "", "", "~/DetailView.aspx?CatID=" + CType(row("CatId"), String) + "&SubCatID=" + CType(row("SubCatId"), String), "_parent") Menu1.Items(count).ChildItems.Add(subCatItems) Next count = count + 1 Next
历史
- 2009年6月28日:初始发布