在模板容器中,放置GridView控件,形成"表中表"的效果,这样可以实现各种复杂的表格效果,下面介绍的"表中表"最适合显示主从表中的数据。

      新建一个ASp.NET网站,在Default.aspx页面中添加如下代码:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>GridView显示主从表数据</title>
    <style type="text/css">
        .PlusMouse{cursor:pointer;}
        .Show{display:block;}
        .Hide{display:none;}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowHeader="false" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <div>
                            <asp:ImageButton ID="imgPlus" runat="server" ImageUrl="~/images/plus.gif" CssClass="PlusMouse" />
                            <asp:Label ID="lblName" runat="server" Text=""></asp:Label>
                        </div>
                        <asp:Panel ID="panelOrder" runat="server" CssClass="Hide" HorizontalAlign="right">
                            <asp:GridView ID="gvOrder" runat="server" AutoGenerateColumns="false" OnRowDataBound="gvOrder_RowDataBound">
                                <Columns>
                                    <asp:TemplateField HeaderText="">
                                        <ItemTemplate>
                                            <asp:Image ID="imgShipState" runat="server" />
                                        </ItemTemplate>
                                        <ItemStyle Width="20px" />
                                    </asp:TemplateField>
                                    <asp:BoundField DataField="OrderID" HeaderText="订单ID">
                                        <ItemStyle Width="60px" />
                                    </asp:BoundField>
                                    <asp:BoundField DataField="CompanyName" HeaderText="顾客公司">
                                        <ItemStyle Width="150px" />
                                    </asp:BoundField>
                                    <asp:BoundField DataField="OrderDate" DataFormatString="{0:yyyy-MM-dd}" HeaderText="订货日期">
                                        <ItemStyle Width="150px" />
                                    </asp:BoundField>
                                    <asp:BoundField DataField="ProductName" HeaderText="产品名称">
                                        <ItemStyle Width="300" />
                                    </asp:BoundField>
                                </Columns>
                            </asp:GridView>
                        </asp:Panel>
                    </ItemTemplate>
                    <ItemStyle Width="700px" />
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

 

在Default.aspx.cs文件中添加如下代码:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    private string conString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];

    protected void Page_Load(object sender, EventArgs e)
    {
        BindEmployee();
    }

    //获取一个DataTable
    private DataTable GetDataTable(string strSQL)
    {
        SqlConnection con = new SqlConnection(conString);
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(strSQL,con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        con.Close();
        return dt;
    }

    private void BindEmployee()
    {
        string strSQL = "select * from Employees";
        this.GridView1.DataSource = this.GetDataTable(strSQL);
        this.GridView1.DataBind();
    }

    private void BindGridOrder(string EmployeeID, GridView gv)
    {
        StringBuilder strSQL = new StringBuilder();
        strSQL.Append("select top 5 t1.OrderID,t1.OrderDate,t1.RequiredDate,t1.ShippedDate,t2.CompanyName,t4.ProductName ");
        strSQL.Append(" from Orders t1 ");
        strSQL.Append(" left join Customers t2 on t1.CustomerID=t2.CustomerID ");
        strSQL.Append(" left join [Order Details] t3 on t1.OrderID = t3.OrderID ");
        strSQL.Append(" left join Products t4 on t3.ProductID = t4.ProductID ");
        strSQL.AppendFormat(" where t1.EmployeeID='{0}'", EmployeeID);
        gv.DataSource = this.GetDataTable(strSQL.ToString());
        gv.DataBind();
    }

    //主表的数据绑定
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType != DataControlRowType.DataRow)
            return;
        DataRowView drv = (DataRowView)e.Row.DataItem;
        Label lblName = (Label)e.Row.FindControl("lblName");
        lblName.Text = drv["TitleOfCourtesy"].ToString() + drv["FirstName"].ToString();

        string pid = e.Row.FindControl("panelOrder").ClientID;
        ImageButton imgPlus = (ImageButton)e.Row.FindControl("imgPlus");
        imgPlus.Attributes.Add("bz","0");
        imgPlus.OnClientClick = "if(this.bz=='0'){ document.getElementById('"+pid+"').className='Show';this.bz='1';}else{ document.getElementById('"+pid+"').className='Hide';this.bz='0';}return false;";
        GridView gv = (GridView)e.Row.FindControl("gvOrder");
        this.BindGridOrder(drv["EmployeeID"].ToString(), gv);
    }

    //从表的数据绑定
    protected void gvOrder_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType != DataControlRowType.DataRow)
            return;
        DataRowView drv = (DataRowView)e.Row.DataItem;
        DateTime requiredDate = DateTime.Parse(drv["RequiredDate"].ToString());
        DateTime shippedDate = requiredDate;
        try
        {
            shippedDate = DateTime.Parse(drv["ShippedDate"].ToString());
        }
        catch
        {
 
        }
        int days = requiredDate.Subtract(shippedDate).Days;
        Image imgState = (Image)e.Row.FindControl("imgShipState");
        if (days < 10)
        {
            imgState.ImageUrl = "./images/1.gif";
        }
        else if (days < 20)
        {
            imgState.ImageUrl = "./images/2.gif";
        }
        else
        {
            imgState.ImageUrl = "./images/3.gif";
        }
    }

   
}
页面显示效果如下:

                                              

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐