利用DataGrid控件显示主-从关系数据表

<%@ Page language="c#" Codebehind="ComputeBySNO.aspx.cs" AutoEventWireup="false" Inherits="DataGridInDataGrid.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>WebForm1</title>
  <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
  <meta content="C#" name="CODE_LANGUAGE">
  <meta content="JavaScript" name="vs_defaultClientScript">
  <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
 </HEAD>
 <body>
  <h2>按学号统计</h2>
  <hr align="left" width="80%" noShade SIZE="4">
  <br>
  <form id="Form1" method="post" runat="server">
   <FONT face="宋体">
    <div align="left">
     <asp:DataGrid id="dgMaster" runat="server" AutoGenerateColumns="False" ShowHeader="False" GridLines="None">
      <Columns>
       <asp:TemplateColumn>
        <ItemTemplate>
         <TABLE style="FONT-SIZE: 13px" width="400" align="center">
          <TR bgColor="#cccccc">
           <TD>学号:<%# DataBinder.Eval(Container.DataItem,"SNO") %></TD>
           <TD>姓名:<%# DataBinder.Eval(Container.DataItem,"SName") %></TD>
           <TD>性别:<%# Convert.ToInt32(DataBinder.Eval(Container.DataItem,"Sex"))==1?"男":"女" %></TD>
          </TR>
          <TR>
           <TD colSpan="3">
            <asp:DataGrid id=dgDetails runat="server" AutoGenerateColumns="False" OnItemDataBound="dgDetails_ItemDataBound" ShowFooter="True" CellPadding="3" BackColor="White" BorderWidth="1px" BorderStyle="None" BorderColor="#CCCCCC" Width="100%" DataSource='<%# ((System.Data.DataRowView)Container.DataItem).CreateChildView("tableRelation") %>'>
             <FooterStyle Font-Size="12px" ForeColor="#000066" BackColor="White"></FooterStyle>
             <SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#669999"></SelectedItemStyle>
             <ItemStyle Font-Size="12px" ForeColor="#000066"></ItemStyle>
             <HeaderStyle Font-Size="12px" Font-Bold="True" ForeColor="White" BackColor="#006699"></HeaderStyle>
             <Columns>
              <asp:TemplateColumn HeaderText="课程名">
               <ItemTemplate>
                <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.CourseName") %>'>
                </asp:Label>
               </ItemTemplate>
               <EditItemTemplate>
                <asp:TextBox runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.CourseName") %>'>
                </asp:TextBox>
               </EditItemTemplate>
              </asp:TemplateColumn>
              <asp:TemplateColumn HeaderText="成绩">
               <ItemTemplate>
                <asp:Label ID="lbl_score" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Grade") %>'>
                </asp:Label>
               </ItemTemplate>
               <EditItemTemplate>
                <asp:TextBox runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Grade") %>'>
                </asp:TextBox>
               </EditItemTemplate>
              </asp:TemplateColumn>
              <asp:TemplateColumn HeaderText="任课教师">
               <ItemTemplate>
                <asp:Label runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Teacher") %>'>
                </asp:Label>
               </ItemTemplate>
               <EditItemTemplate>
                <asp:TextBox runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Teacher") %>'>
                </asp:TextBox>
               </EditItemTemplate>
              </asp:TemplateColumn>
             </Columns>
             <PagerStyle HorizontalAlign="Left" ForeColor="#000066" BackColor="White" Mode="NumericPages"></PagerStyle>
            </asp:DataGrid></TD>
          </TR>
          <TR>
           <TD colSpan="3">
            <HR>
           </TD>
          </TR>
         </TABLE>
        </ItemTemplate>
       </asp:TemplateColumn>
      </Columns>
     </asp:DataGrid></div>
   </FONT>
  </form>
 </body>
</HTML>
--------------------------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

namespace DataGridInDataGrid
{
 /// <summary>
 /// WebForm1 的摘要说明。
 /// </summary>
 public class WebForm1 : System.Web.UI.Page
 {
  private int SumScore=0;
  private int MaxScore=0;
  private int MinScore=100;//每门课的满分为100

  protected System.Web.UI.WebControls.DataGrid dgMaster;
  protected System.Web.UI.WebControls.DataGrid DataGrid2;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   if(!Page.IsPostBack)
   {
    this.BindData();
   }
  }

  private void BindData()
  {
   SqlConnection MyCn=new SqlConnection();
   MyCn.ConnectionString=@"Server=BOBO\PLAYBOY;Database=StudyStatus;Uid=sa;Pwd=840616";
  
   string str_sql = @"select * from students;select SNO,Course.CourseName,Score.Grade,Course.Teacher from Score,Course where Score.CourseNum=Course.CourseNum";
   SqlDataAdapter Myda=new SqlDataAdapter(str_sql,MyCn);

   DataSet ds=new DataSet();
   Myda.Fill(ds);
   ds.Tables[0].TableName="students";
   ds.Tables[1].TableName="Score";

   DataColumn parent=ds.Tables["students"].Columns["SNO"];
   DataColumn child=ds.Tables["Score"].Columns["SNO"];

   DataRelation tableRelation=new DataRelation("tableRelation",parent,child,false);
   ds.Relations.Add(tableRelation);

   
   this.dgMaster.DataSource=ds.Tables["students"].DefaultView;
   this.dgMaster.DataBind();
  }

  /// <summary>
  /// 模板列中的 DataGrid控件 的ItemDataBound事件
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  public void dgDetails_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
  {
   DataGrid dg=(DataGrid)(e.Item.Parent.Parent);
  
   if(e.Item.ItemIndex>=0)
   {
    Label lbl_score=(Label)e.Item.Cells[1].FindControl("lbl_score");
    int CurScore=int.Parse(lbl_score.Text);
    
    this.SumScore+=CurScore;
    if(this.MaxScore<CurScore)
    {
     this.MaxScore=CurScore;
    }
    if(this.MinScore>CurScore)
    {
     this.MinScore=CurScore;
    }
   }

   if(e.Item.ItemType==ListItemType.Footer)
   {
    if(dg.Items.Count!=0)
    {
     e.Item.Cells[0].Text="成绩统计:[总分]"+this.SumScore.ToString()+"    [平均分]"+String.Format("{0:N2}",(float)SumScore/(float)dg.Items.Count);
     e.Item.Cells[1].Text="[最高分]"+this.MaxScore.ToString();
     e.Item.Cells[2].Text="[最低分]"+this.MinScore.ToString();

     //绑定完后,数据恢复
     this.SumScore=this.MaxScore=0;
     this.MinScore=100;
    }
   }
  }
  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion
 }
}

<%@ Page language="c#" Codebehind="ComputeBySNO.aspx.cs" AutoEventWireup="false" Inherits="DataGridInDataGrid.WebForm1" %>
posted @ 2007-02-11 12:11  RobotTech  阅读(522)  评论(0编辑  收藏  举报