- 作者:xiaoxiao
- 发表时间:2020-12-23 10:34
- 来源:未知
利用ASP.NET DataGrid显示主次关系的数据 |
作者:孟宪会 出自:【孟宪会之精彩世界】 发布日期:2003年4月18日 12点0分0秒
|
大家在实际工作中有没有遇到要在DataGrid中显示带有主次结构的数据呢?如果你对ADO.NET和SQL Server2000熟悉的话,我们下面就举一个利用VS.NET自带的示例数据库Northwind和VB.NET来说明如何实现这一目标。 首先,我们先准备要显示的带有主次结构的数据。 下面就是要绑定到HierarchicalDataGrid.aspx的VB.NET代码文件HierarchicalDataGrid.aspx.vb的内容: Imports System.Data.SqlClientPublic Class HierarchicalDataGridInherits System.Web.UI.PageProtected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid#Region " Web Form Designer Generated Code "'下面的调用对Web Form设计器来说是必须的<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()End SubPrivate Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init'CODEGEN: 这个方法是为Web Form设计器调用的'不要用代码编辑器改变这里.InitializeComponent()End Sub#End RegionPrivate Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load'打开数据库连接Dim OrdersConnection As New SqlConnection("Server=(local)/NetSDK;Database=northwind;Trusted_Connection=yes")'得到订单和订单详细信息Dim OrderAdapter As New SqlDataAdapter("Select * from Orders; select OrderID ,Products.ProductName,[order Details].Unitprice,[order Details].Quantity,[order Details].discount from [order Details],Products where [Order Details].ProductId=Products.ProductID", OrdersConnection)'创建并填充DataSet对象Dim OrderDataSet As New DataSet()OrderAdapter.Fill(OrderDataSet)'设定表名字OrderDataSet.Tables(0).TableName = "Orders"OrderDataSet.Tables(1).TableName = "Order Details"'在基于OrderID字段的两个表之间建立父子关系Dim Parent As DataColumn = OrderDataSet.Tables("Orders").Columns("OrderID")Dim Child As DataColumn = OrderDataSet.Tables("Order Details").Columns("OrderID")Dim OrderRelation As DataRelation = New DataRelation("OrderRelation", Parent, Child, False)'为DataSet添加关系OrderDataSet.Relations.Add(OrderRelation)'把DataGrid绑定到Orders表DataGrid1.DataSource = OrderDataSet.Tables("Orders").DefaultViewDataBind()End SubPrivate Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid1.ItemDataBounde.Item.Cells(0).BackColor = System.Drawing.Color.IvoryEnd SubEnd Class |