日期:2008-11-06  浏览次数:20440 次


表dep:depid(标识主键),depname(学院名字)
表stu:stuid(标识主键),stuname(学生名字),studepid(学院id=表dep.depid)

前台:
<%@ Page language="c#" Codebehind="WebForm30.aspx.cs" AutoEventWireup="false" Inherits="csdn.WebForm30" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>WebForm30</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <link href="css.css" rel="stylesheet" type="text/css">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
  </form>
 </body>
</HTML>
后台:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;


namespace csdn
{
 /// <summary>
 /// WebForm30 的摘要说明。
 /// </summary>
 public class WebForm30 : System.Web.UI.Page
 {
  DataGrid DataGrid1=new DataGrid();
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   CreateDataGrid(); 
  }
  
  protected void CreateDataGrid()
  {
   DataGrid1.AutoGenerateColumns=false;
   DataGrid1.CssClass="border";
   DataGrid1.BorderWidth=0;
   DataGrid1.CellSpacing=1;
   DataGrid1.CellPadding=5;
   DataGrid1.ItemStyle.CssClass="item";
   DataGrid1.HeaderStyle.CssClass="header";
   DataGrid1.DataKeyField="stuid";
//以上设定DataGrid的样式
   TemplateColumn tm=new TemplateColumn();
   tm.ItemTemplate=new ColumnTemplate1();
   tm.HeaderText="姓名";
   DataGrid1.Columns.Add(tm);
//建立第一个模板列
   TemplateColumn tm2=new TemplateColumn();
   tm2.ItemTemplate=new ColumnTemplate2();
   tm2.HeaderText="学院";
   DataGrid1.Columns.Add(tm2);
//建立第二个模板列
   ButtonColumn bc=new ButtonColumn();
   bc.ButtonType=ButtonColumnType.PushButton;
   bc.CommandName="del";
   bc.Text="删除";
   DataGrid1.Columns.Add(bc);
//建立删除按钮列
   SetBind();
//填充数据
   Page.Controls[1].Controls.Add(DataGrid1);
//给页面的form加入这个DataGrid1
  }

  protected void SetBind()
  {
   SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
   SqlDataAdapter da=new SqlDataAdapter("select * from stu,dep where stu.studepid=dep.depid",conn);
   DataSet ds=new DataSet();
   da.Fill(ds,"table1");
   this.DataGrid1.DataSource=ds.Tables["table1"];
   this.DataGrid1.DataBind();
   
  }

  private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
  {
//和上面连接给出的例子中的代码一样,给下拉框绑定数据,并且选择默认的
   SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
  &