天天看點

asp.net利用GridView"表中表"實作主從表資料

      在模闆容器中,放置GridView控件,形成"表中表"的效果,這樣可以實作各種複雜的表格效果,下面介紹的"表中表"最适合顯示主從表中的資料。

      建立一個ASp.NET網站,在Default.aspx頁面中添加如下代碼:

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

<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 DataField="OrderDate" DataFormatString="{0:yyyy-MM-dd}" HeaderText="訂貨日期">

                                    <asp:BoundField DataField="ProductName" HeaderText="産品名稱">

                                        <ItemStyle Width="300" />

                                </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)

        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";

}

頁面顯示效果如下:

繼續閱讀