这是我这个菜鸟做的入门级的程序,与菜鸟们一起分享~~~~~基本效果图:
(程序主页面图(子表的信息可显示和隐藏))
(showModalDialog弹出的修改子窗口,可根据情况刷新父窗口)
一.开发环境:
.net 版本:asp.net 1.1.4322.2032
工具:Visual Studio 2003
操作系统:Window Server 2003
数据库:SqlServer 2000
二.程序功能:
1.利用DataRelation在DataGrid中显示主从表信息,从表的信息可以显示/隐藏.
2.支持分页(系统默认分页),支持主表和从表的增加/更新/删除.
3.简要需求说明:
(1)班次(EPM_WorkTime表和班次的值班区间(EPM_WorkTimeChild表之间是一对多的关系.(也许这里没必要这样麻烦,但为了学习,所以如此做了.)
CREATE TABLE [EPM_WorkTimeChild] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[parentid] [int] NOT NULL ,
[timestart] [varchar] (20) COLLATE Chinese_PRC_CI_AS NULL ,
[timeend] [varchar] (20) COLLATE Chinese_PRC_CI_AS NULL ,
CONSTRAINT [PK_EPM_WorkTimeChild] PRIMARY KEY CLUSTERED
(
[id]
) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [EPM_WorkTime] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[name] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL
CONSTRAINT [PK_EPM_WorkTime] PRIMARY KEY CLUSTERED
(
[id]
) ON [PRIMARY]
) ON [PRIMARY]
GO
(2)从表中使用了ViewState{"Id"]来保存Request.QueryString方式传递过来的parentid;因为多处用到它,所以使用了ViewStae而不是每次Request.ueryString来获得,不知这里是否合适.
(3)其中的一些JS脚本可以通过注册的方式后台添加,这里没有这样,大都写在ASPX文件中了.
数据库访问没有使用Enterprise Library 等比较好的数据访问封装,对这些不太熟悉.而是拼凑了别人的数据访问类.
(4)子窗口中若选择了确定,则返回后刷新父窗口(因为内容更新了),若选择取消则不刷新父窗口.
(5)关键是下面的一行代码,比葫芦画瓢能用了,但不理解.
DataSource='
<%
# ((System.Data.DataRowView)(Container.DataItem)).CreateChildView("WorkTime")
%>
'
三.具体程序代码:
WorkTimeManage.aspx:
1
<%
@ Page language="c#" Codebehind="WorkTimeManage.aspx.cs" AutoEventWireup="false" Inherits="EPNew.WorkTimeManage" SmartNavigation ="true"
%>
2
<!
DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
>
3
<
HTML
>
4
<
HEAD
>
5
<
title
>
WorkTimeManage
</
title
>
6
<
meta
content
="Microsoft Visual Studio .NET 7.1"
name
="GENERATOR"
>
7
<
meta
content
="C#"
name
="CODE_LANGUAGE"
>
8
<
meta
content
="JavaScript"
name
="vs_defaultClientScript"
>
9
<
meta
content
="http://schemas.microsoft.com/intellisense/ie5"
name
="vs_targetSchema"
>
10
<
SCRIPT
language
="JavaScript"
>
11 <!--
12 //展开和关闭时候显示/隐藏子表信息
13 function showDiv(img,div)
14 {
15 var img = document.getElementById(img);
16 var div = document.getElementById(div);
17 var picName = img.src;
18 picName = picName.substring(picName.lastIndexOf("/")+1);
19 if (picName.toLowerCase() == "close.gif")
20 {
21 div.style.display ="block";
22 img.src = "images/open.gif";
23 }
24 else
25 {
26 div.style.display ="none";
27 img.src = "images/close.gif";
28 }
29 }
30
31
32 //-->
33
</
SCRIPT
>
34
</
HEAD
>
35
<
body
MS_POSITIONING
="FlowLayout"
>
36
<
form
id
="Form1"
method
="post"
runat
="server"
>
37
<
TABLE
id
="Table1"
cellSpacing
="1"
cellPadding
="1"
width
="100%"
border
="0"
>
38
<
TR
class
="Title"
>
39
<
TD
align
="center"
>
班次列表
</
TD
>
40
</
TR
>
41
<
TR
class
="Title"
>
42
<
TD
align
="left"
>
值班班次名称:
43
<
asp:textbox
id
="TxtName"
runat
="server"
></
asp:textbox
>
44
<
asp:button
id
="BtnAdd"
runat
="server"
Text
="增加值班班次"
></
asp:button
></
TD
>
45
</
TR
>
46
<
TR
>
47
<
TD
><
asp:datagrid
id
="DataGrid1"
runat
="server"
DataKeyField
="id"
Width
="100%"
AutoGenerateColumns
="False"
48
ShowHeader
="False"
BackColor
="#fffff6"
AllowPaging
="True"
PageSize
="3"
>
49
<
Columns
>
50
<
asp:TemplateColumn
>
51
<
ItemTemplate
>
52
<
TABLE
border
="0"
width
="100%"
>
53
<
TR
>
54
<
TD
width
="70"
>
55
<
asp:Label
ID
="LblId"
Runat
="server"
Visible
="False"
text
='<%#
DataBinder.Eval(Container.DataItem,"id")%
>
'>
56
</
asp:Label
>
57
58
<
asp:Image
ID
="ImgOpen"
Runat
="server"
open
="true"
style
="cursor:hand"
ImageUrl
="images/close.gif"
></
asp:Image
></
TD
>
59
<
td
>
60
<
asp:Label
ID
="LblName"
Runat
="server"
Text
='<%#
DataBinder.Eval(Container.DataItem,"Name")%
>
'>
61
</
asp:Label
>
62
</
td
>
63
<
td
width
="150"
>
64
<
asp:LinkButton
ID
="LbtnEdit"
Runat
="server"
Text
="修改"
></
asp:LinkButton
>
65
66
<
asp:LinkButton
ID
="LbtnDel"
Runat
="server"
Text
="删除"
CommandName
="Delete"
></
asp:LinkButton
>
67
</
td
>
68
</
TR
>
69
<
TR
>
70
<
TD
colspan
="3"
align
="center"
bgcolor
="#fefefe"
>
71
<
asp:Panel
ID
="PnlContent"
Runat
="server"
style
="display:none"
Border
="0"
>
72
<
asp:DataGrid
ID
="DgContent"
Runat
="server"
Width
="80%"
DataKeyField
="id"
AutoGenerateColumns
= "False"
BorderColor
="#3677B1"
BackColor
="#fefefe"
73
DataSource
='<%#
((System.Data.DataRowView)(Container.DataItem)).CreateChildView("WorkTime") %
>
'>
74
<
Columns
>
75
<
asp:BoundColumn
DataField
="id"
HeaderText
="序号"
HeaderStyle-HorizontalAlign
="Center"
></
asp:BoundColumn
>
76
<
asp:BoundColumn
DataField
="TimeStart"
HeaderText
="开始时间"
HeaderStyle-HorizontalAlign
="Center"
></
asp:BoundColumn
>
77
<
asp:BoundColumn
DataField
="TimeEnd"
HeaderText
="结束时间"
HeaderStyle-HorizontalAlign
="Center"
></
asp:BoundColumn
>
78
</
Columns
>
79
</
asp:DataGrid
>
80
</
asp:Panel
>
81
</
TD
>
82
</
TR
>
83
</
TABLE
>
84
</
ItemTemplate
>
85
</
asp:TemplateColumn
>
86
</
Columns
>
87
<
PagerStyle
Mode
="NumericPages"
></
PagerStyle
>
88
</
asp:datagrid
></
TD
>
89
</
TR
>
90
<
TR
>
91
<
TD
></
TD
>
92
</
TR
>
93
</
TABLE
>
94
</
form
>
95
</
body
>
96
</
HTML
>
97
WorkTimeManage.aspx.cs
1
using
System;
2
using
System.Collections;
3
using
System.ComponentModel;
4
using
System.Data;
5
using
System.Data.SqlClient;
6
using
System.Drawing;
7
using
System.Web;
8
using
System.Web.SessionState;
9
using
System.Web.UI;
10
using
System.Web.UI.WebControls;
11
using
System.Web.UI.HtmlControls;
12
13
namespace
EPNew
14
{
15 /**//// <summary>
16 /// WorkTimeManage 的摘要说明。
17 /// </summary>
18 public class WorkTimeManage : System.Web.UI.Page
19 {
20 protected System.Web.UI.WebControls.DataGrid DataGrid1;
21 protected System.Web.UI.WebControls.TextBox TxtName;
22 protected System.Web.UI.WebControls.Button BtnAdd;
23
24 //数据访问实例
25 protected ClassConn connE = new ClassConn();
26
27 private void Page_Load(object sender, System.EventArgs e)
28 {
29 // 在此处放置用户代码以初始化页面
30 if(!IsPostBack)
31 {
32 //绑定数据
33 InitData();
34 }
35 }
36
37 /**//// <summary>
38 /// 初始化数据
39 /// </summary>
40 private void InitData()
41 {
42 string strSql = "select id,name from EPM_WorkTime order by id ;select * from EPM_WorkTimeChild ";
43 DataSet ds = connE.getDs(strSql);
44 ds.Tables[0].TableName = "farther";
45 ds.Tables[1].TableName = "child";
46 DataColumn dcFarther = ds.Tables["farther"].Columns["id"];
47 DataColumn dcChild = ds.Tables["child"].Columns["parentid"];
48 //主从表的关联
49 DataRelation dRelation = new DataRelation("WorkTime",dcFarther,dcChild,true);
50 ds.Relations.Add(dRelation);
51 DataGrid1.DataSource = ds.Tables["farther"].DefaultView;
52 DataGrid1.DataBind();
53
54 }
55 Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码
56 override protected void OnInit(EventArgs e)
57 {
58 //
59 // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
60 //
61 InitializeComponent();
62 base.OnInit(e);
63 }
64
65 /**//// <summary>
66 /// 设计器支持所需的方法 - 不要使用代码编辑器修改
67 /// 此方法的内容。
68 /// </summary>
69 private void InitializeComponent()
70 {
71 this.BtnAdd.Click += new System.EventHandler(this.BtnAdd_Click);
72 this.DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndexChanged);
73 this.DataGrid1.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_DeleteCommand);
74 this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);
75 this.Load += new System.EventHandler(this.Page_Load);
76
77 }
78 #endregion
79
80
81 /**//// <summary>
82 /// 设置修改按钮打开窗口的JS事件
83 /// 设置展开图片的JS事件.
84 /// 设置删除确认的JS事件
85 /// </summary>
86 /// <param name="sender"></param>
87 /// <param name="e"></param>
88 private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
89 {
90 Label lblName = (Label) e.Item.FindControl("LblName");
91 LinkButton lbtn = (LinkButton) e.Item.FindControl("LbtnEdit");
92 Label lbl = (Label) (e.Item.FindControl("LblId"));
93 System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)(e.Item.FindControl("ImgOpen"));
94 Panel pnl = (Panel)(e.Item.FindControl("PnlContent"));
95 LinkButton lbtnDel = (LinkButton) (e.Item.FindControl("LbtnDel"));
96 if(img != null && pnl != null && lbtn != null && lbl!= null && lbtnDel != null && lblName != null)
97 {
98 //修改按钮打开窗口的js事件
99 lbtn.Attributes.Add("onclick","var obj = showModalDialog(\"WorkTimeChildManage.aspx?id="+lbl.Text+"&name="
100 +Server.UrlEncode(lblName.Text)+"\",\"workchild\",\"dialogWidth:500px; dialogHeight:500px;help:0;"
101 +"status:0;resizeable:1\");if(obj==\"true\") location.reload(); else return false;");
102 //lbtn.Attributes.Add("onclick","var obj = window.open(\"EmployeeSetPower.aspx?id="+strId+"\");if(obj==false) return false;");
103 //展开图片的JS事件.
104 img.Attributes.Add("onclick","showDiv('"+img.ClientID+"','"+pnl.ClientID+"');return false;");
105 //删除确认
106 lbtnDel.Attributes.Add("onclick","return confirm('该班次的所有值班区间也将删除,确实要删除?');");
107 }
108
109 }
110
111 /**//// <summary>
112 /// 页码更改事件
113 /// </summary>
114 /// <param name="source"></param>
115 /// <param name="e"></param>
116 private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
117 {
118 DataGrid1.CurrentPageIndex = e.NewPageIndex;
119 //绑定数据
120 InitData();
121 }
122
123 /**//// <summary>
124 /// 删除值班班次,同时删除两个表的记录(EPM_WorkTime和EPM_WorkTimeChild).
125 /// </summary>
126 /// <param name="source"></param>
127 /// <param name="e"></param>
128 private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
129 {
130 //程序级事务删除
131 string strId = DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
132 connE.Open();
133 SqlTransaction trans = connE.conn.BeginTransaction();
134 SqlCommand cmd = new SqlCommand();
135 cmd.Connection = connE.conn;
136 cmd.Transaction = trans;
137 try
138 {
139 cmd.CommandText= "delete from EPM_WorkTimeChild where parentid ="+strId;
140 cmd.ExecuteNonQuery();
141 cmd.CommandText = "delete from EPM_WorkTime where id ="+strId;
142 cmd.ExecuteNonQuery();
143 trans.Commit();
144 }
145 catch(SqlException Ex1)
146 {
147 trans.Rollback();
148 Response.Write(Ex1.ToString());
149
150 }
151 finally
152 {
153 trans.Dispose();
154 connE.Close();
155 }
156 //为了防止某页数据只剩一条记录删除后发生的错误,要判断当前页的记录数和当前页码
157 if(DataGrid1.Items.Count ==1 && DataGrid1.CurrentPageIndex>0)
158 {
159 DataGrid1.CurrentPageIndex --;
160 }
161 //重新绑定数据
162 InitData();
163 }
164
165 /**//// <summary>
166 /// 增加一值班班次
167 /// </summary>
168 /// <param name="sender"></param>
169 /// <param name="e"></param>
170 private void BtnAdd_Click(object sender, System.EventArgs e)
171 {
172 connE.builder("select top 1 * from EPM_WorkTime");
173 connE.dr["name"] = this.TxtName.Text.Trim();
174 connE.builderClose();
175 DataGrid1.CurrentPageIndex = 0;
176 //重新绑定数据
177 InitData();
178 }
179 }
180}
181
四.备注:
本文参考了:
利用ASP.NET DataGrid显示主次关系的数据
http://dotnet.aspx.cc/ShowDetail.aspx?id=149E5DD7-3B32-461e-ACC6-51D1652E6746