大家在实际工作中有没有遇到要在DataGrid中显示带有主次结构的数据呢?如果你对ADO.NET和SQL Server2000熟悉的话,我们下面就举一个利用VS.NET自带的示例数据库Northwind和VB.NET来说明如何实现这一目标。
首先,我们先准备要显示的带有主次结构的数据。
下面就是要绑定到HierarchicalDataGrid.aspx的VB.NET代码文件HierarchicalDataGrid.aspx.vb的内容:
\n
Imports System.Data.SqlClient
\n
Public Class HierarchicalDataGrid
Inherits System.Web.UI.Page
Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid
\n
#Region ” Web Form Designer Generated Code “
\n
‘下面的调用对Web Form设计器来说是必须的
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
\n
End Sub
\n
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
‘CODEGEN: 这个方法是为Web Form设计器调用的
‘不要用代码编辑器改变这里.
InitializeComponent()
End Sub
\n
#End Region
\n
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
\n
‘打开数据库连接
Dim OrdersConnection As New SqlConnection(“Server=(local)\\NetSDK;Database=northwind;Trusted_Connection=yes”)
\n
‘得到订单和订单详细信息
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)
\n
‘创建并填充DataSet对象
Dim OrderDataSet As New DataSet()
\n
OrderAdapter.Fill(OrderDataSet)
\n
‘设定表名字
OrderDataSet.Tables(0).TableName = “Orders”
OrderDataSet.Tables(1).TableName = “Order Details”
\n
‘在基于OrderID字段的两个表之间建立父子关系
Dim Parent As DataColumn = OrderDataSet.Tables(“Orders”).Columns(“OrderID”)
Dim Child As DataColumn = OrderDataSet.Tables(“Order Details”).Columns(“OrderID”)
\n
Dim OrderRelation As DataRelation = New DataRelation(“OrderRelation”, Parent, Child, False)
\n
‘为DataSet添加关系
OrderDataSet.Relations.Add(OrderRelation)
\n
‘把DataGrid绑定到Orders表
DataGrid1.DataSource = OrderDataSet.Tables(“Orders”).DefaultView
DataBind()
\n
End Sub
\n
Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid1.ItemDataBound
e.Item.Cells(0).BackColor = System.Drawing.Color.Ivory
End Sub
End Class
\n
在HierarchicalDataGrid.aspx中,我们为DataGrid1建立模板列,并把另外一个DataGrid嵌入到这个模板列,父一级的DataGrid用来显示主记录,比如:订单。子一级DataGrid用来显示详细信息,比如:订单的详细信息。我们这样为子DataGrid动态指定数据源:
\n
DataSource=’<%# Ctype(Container.DataItem,DataRowView).CreateChildView(“OrderRelation”) %>’>
\n
上面这句就是实现显示主次关系数据的关键。根据当前父一级记录,DataRowView.CreateChildView利用前面创建的关系的名字作为参数获得子记录,并把它绑定到子DataGrid上。
\n
下面就是我们要显示的ASPX页面的代码,HierarchicalDataGrid.aspx:
\n
<%@ Page Language=”vb” AutoEventWireup=”false” Codebehind=”HierarchicalDataGrid.aspx.vb” Inherits=”HierarchicalDataGrid.HierarchicalDataGrid” %>
<%@ Import namespace=”System.Data”%>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<HTML>
<HEAD>
<title>显示主次关系数据的例子</title>
<meta name=”GENERATOR” content=”Microsoft Visual Studio.NET 7.0″>
<meta name=”CODE_LANGUAGE” content=”Visual Basic 7.0″>
<meta name=”vs_defaultClientScript” content=”JavaScript”>
<meta name=”vs_targetSchema” content=”http://schemas.microsoft.com/intellisense/ie5″>
</HEAD>
<body>
<form id=”FrmDataGrid” method=”post” runat=”server”>
<P align=”center”>
<asp:DataGrid id=”DataGrid1″ BorderColor=”#0099FF” runat=”server” ShowHeader=”False” Width=”470px” CellPadding=”0″ CellSpacing=”0″ AutoGenerateColumns=”False” BorderWidth=”2px”>
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<TABLE cellSpacing=”0″ cellPadding=”0″ width=”100%” border=”0″>
<TR>
<TD bgColor=”#FF6600″><B>订单号:
<%# DataBinder.Eval(Container.DataItem, “OrderID”) %>
</B>
</TD>
</TR>
<TR>
<TD align=”right”>
<asp:DataGrid id=DataGrid2 runat=”server” AutoGenerateColumns=”False” BorderColor=”#33FF33″ DataKeyField=”OrderID” DataSource=’<%# Ctype(Container.DataItem,DataRowView).CreateChildView(“OrderRelation”) %>’>
<HeaderStyle Font-Bold=”True” ForeColor=”#CC0066″ BackColor=”#FFCCFF”></HeaderStyle>
<Columns>
<asp:BoundColumn Visible=”False” DataField=”OrderID” ReadOnly=”True”></asp:BoundColumn>
<asp:TemplateColumn HeaderText=”产品名称”>
<HeaderStyle Width=”300px”></HeaderStyle>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, “ProductName”) %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField=”UnitPrice” HeaderText=”单价”></asp:BoundColumn>
<asp:BoundColumn DataField=”Quantity” HeaderText=”数量”></asp:BoundColumn>
<asp:BoundColumn DataField=”Discount” HeaderText=”折扣”></asp:BoundColumn>
</Columns>
</asp:DataGrid></TD>
</TR>
</TABLE>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid></P>
</form>
</body>
</HTML>
\n
在VS.NET里创建名字为HierarchicalDataGrid的VB.NET ASPX应用程序,输入上面的代码,就可以看到下面的结果:
\n
\n
ASP.NET 2.0版本代码
\n
C#
\n
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Test_Default” %>
\n
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>无标题页</title>
</head>
<body>
<form runat=”server”>
<asp:DataGrid ID=”DataGrid1″ BorderColor=”#0099FF” runat=”server” ShowHeader=”False”
Width=”470px” CellPadding=”0″ CellSpacing=”0″ AutoGenerateColumns=”False” BorderWidth=”2px”
OnItemDataBound=”DataGrid1_ItemDataBound”>
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<table cellspacing=”0″ cellpadding=”0″ width=”100%” border=”0″>
<tr>
<td bgcolor=”#FF6600″>
<b>订单号:
<%# Eval(“OrderID”) %>
</b>
</td>
</tr>
<tr>
<td align=”right”>
<asp:DataGrid ID=”DataGrid2″ runat=”server” AutoGenerateColumns=”False” BorderColor=”#33FF33″
DataKeyField=”OrderID” DataSource=’<%# ((System.Data.DataRowView)Container.DataItem).CreateChildView(“OrderRelation”) %>’>
<HeaderStyle Font-Bold=”True” ForeColor=”#CC0066″ BackColor=”#FFCCFF”></HeaderStyle>
<Columns>
<asp:BoundColumn Visible=”False” DataField=”OrderID” ReadOnly=”True”></asp:BoundColumn>
<asp:TemplateColumn HeaderText=”产品名称”>
<HeaderStyle Width=”300px”></HeaderStyle>
<ItemTemplate>
<%# Eval(“ProductName”) %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField=”UnitPrice” HeaderText=”单价”></asp:BoundColumn>
<asp:BoundColumn DataField=”Quantity” HeaderText=”数量”></asp:BoundColumn>
<asp:BoundColumn DataField=”Discount” HeaderText=”折扣”></asp:BoundColumn>
</Columns>
</asp:DataGrid></td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</form>
</body>
</html>
\n
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
\n
public partial class _Test_Default : System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e )
{
SqlConnection OrdersConnection = new SqlConnection(@”User ID=sa;Password=;Initial Catalog=NorthWind;Server=(local)”);
SqlDataAdapter OrderAdapter = 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 OrderDataSet = new DataSet();
OrderAdapter.Fill(OrderDataSet);
OrderDataSet.Tables[0].TableName = “Orders”;
OrderDataSet.Tables[1].TableName = “Order Details”;
DataColumn Parent = OrderDataSet.Tables["Orders"].Columns["OrderID"];
DataColumn Child = OrderDataSet.Tables["Order Details"].Columns["OrderID"];
DataRelation OrderRelation = new DataRelation(“OrderRelation”, Parent, Child, false);
OrderDataSet.Relations.Add(OrderRelation);
DataGrid1.DataSource = OrderDataSet.Tables["Orders"].DefaultView;
DataBind();
}
protected void DataGrid1_ItemDataBound( object sender, DataGridItemEventArgs e )
{
e.Item.Cells[0].BackColor = System.Drawing.Color.Ivory;
}
}
\n
VB.NET
\n
<%@ Page Language=”VB” AutoEventWireup=”false” CodeFile=”Default3.aspx.vb” Inherits=”Default3″ %>
\n
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head id=”Head1″ runat=”server”>
<title>无标题页</title>
</head>
<body>
<form id=”Form1″ runat=”server”>
<asp:DataGrid ID=”DataGrid1″ BorderColor=”#0099FF” runat=”server” ShowHeader=”False”
Width=”470px” CellPadding=”0″ CellSpacing=”0″ AutoGenerateColumns=”False” BorderWidth=”2px”>
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<table cellspacing=”0″ cellpadding=”0″ width=”100%” border=”0″>
<tr>
<td bgcolor=”#FF6600″>
<b>订单号:
<%# Eval(“OrderID”) %>
</b>
</td>
</tr>
<tr>
<td align=”right”>
<asp:DataGrid ID=”DataGrid2″ runat=”server” AutoGenerateColumns=”False” BorderColor=”#33FF33″
DataKeyField=”OrderID” DataSource=’<%# CType(Container.DataItem,System.Data.DataRowView).CreateChildView(“OrderRelation”) %>’>
<HeaderStyle Font-Bold=”True” ForeColor=”#CC0066″ BackColor=”#FFCCFF”></HeaderStyle>
<Columns>
<asp:BoundColumn Visible=”False” DataField=”OrderID” ReadOnly=”True”></asp:BoundColumn>
<asp:TemplateColumn HeaderText=”产品名称”>
<HeaderStyle Width=”300px”></HeaderStyle>
<ItemTemplate>
<%# Eval(“ProductName”) %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField=”UnitPrice” HeaderText=”单价”></asp:BoundColumn>
<asp:BoundColumn DataField=”Quantity” HeaderText=”数量”></asp:BoundColumn>
<asp:BoundColumn DataField=”Discount” HeaderText=”折扣”></asp:BoundColumn>
</Columns>
</asp:DataGrid></td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</form>
</body>
</html>
\n
Partial Class Default3
Inherits System.Web.UI.Page
\n
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim OrdersConnection As System.Data.SqlClient.SqlConnection =
New System.Data.SqlClient.SqlConnection(“User ID=sa;Password=;Initial Catalog=NorthWind;Server=(local)”)
Dim OrderAdapter As System.Data.SqlClient.SqlDataAdapter = New
System.Data.SqlClient.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)
Dim OrderDataSet As System.Data.DataSet = New System.Data.DataSet()
OrderAdapter.Fill(OrderDataSet)
OrderDataSet.Tables(0).TableName = “Orders”
OrderDataSet.Tables(1).TableName = “Order Details”
\n
Dim Parent As System.Data.DataColumn = OrderDataSet.Tables(“Orders”).Columns(“OrderID”)
Dim Child As System.Data.DataColumn = OrderDataSet.Tables(“Order Details”).Columns(“OrderID”)
Dim OrderRelation As System.Data.DataRelation = New System.Data.DataRelation(“OrderRelation”, Parent, Child, False)
OrderDataSet.Relations.Add(OrderRelation)
DataGrid1.DataSource = OrderDataSet.Tables(“Orders”).DefaultView
DataBind()
End Sub
\n
Protected Sub DataGrid1_ItemDataBound(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid1.ItemDataBound
e.Item.Cells(0).BackColor = System.Drawing.Color.Ivory
End Sub
End Class
\n
来源: 孟宪会之精彩世界