点击gridview智能标签【编辑列】添加一个HyperLinkField字段,设置相关属性:
HeaderText | 员工资料 |
Text | 点击查看详细资料 |
DataNavigateUrlField | realname,jobnum |
DatanavigateUrlFormatString | ClerkDetail.aspx?realname={0}&jobnum={1} |
DataTextField | realname |
DataTextFormatString | 查看{0}的详细资料 |
创建ClerkDetail.aspx页
在页面中拖入sqlDataSource控件,在页面中拖入detailview控件,指定数据源为sqlDataSource1,点击sqlDataSource的SelectQuery属性,配置 命令和参数编辑器 对话框

运行后结果如下:
ClerkID | 3 |
RealName | 张大客 |
JobNum | 3001 |
DeptID | 3 |
ClerkID | 2 |
RealName | 王公客 |
JobNum | 1002 |
DeptName | 公客部 |
以上的处理几乎没有编写任何程序代码,如何用代码来实现以上功能?
ClerkDetail.aspx也只有两个控件detailsview,sqldatasource,不做任何数据源绑定,编码如下:



























如果想把两个gridview显示在一个页面中应该怎么办呢?
为了实现这一点,需要能取得第一个gridview的clerkID,并且将他传给第二个gridview
我们在第一个gridview中添加 选择按钮,用启用选择,并且在编辑列中将buttonType设成button
创建第二个gridview,创建第二个sqldatasource,并配置select语句的where选项,设置为:

点击添加,点击确定。
页面运行结果如下:
员工编号 | 姓名 | 员工明细 | |
---|---|---|---|
0001 | 陈公客 | 查看陈公客的详细资料 | |
0002 | 王公客 | 查看王公客的详细资料 | |
0003 | 张大客 | 查看张大客的详细资料 | |
0004 | 李大客 | 查看李大客的详细资料 |
ClerkID | RealName | JobNum | DeptID |
---|---|---|---|
1 | 陈公客 | 1001 | 1 |
我们看到SqlDataSource控件能够搭配 QueryStringPararmeter或者ControlParameter里面的参数来构造select语句,其实它还支持CookieParameter,FormParameter,ProfileParameter,SessionParameter等六个参数类型。
利用这个特性,我们增强ClerkList.aspx的功能,提供部门下拉列表选框,根据不同的部门选择来显示相关部门的员工列表。
首先增加数据源sqldsDeptList,部门下拉框DeptDropList,绑定数据源sqldsDeptList,并将其AutoPostBack设成True
数据源使用自定义select语句:SELECT DeptID, DeptName, ParentDeptID, AreaID FROM dbo.CODE_Dept WHERE (AreaID = 1)
增加SqlDataSource数据源sqldsClerkList,GridView员工列表ClerkGridView控件,配置sqldsClerkList的Where参数,选择DeptID来自DeptDropList控件。
运行结果如下:
ClerkID | RealName | JobNum |
---|---|---|
3 | 张大客 | 3001 |
4 | 李大客 | 3002 |
为了能够添加,删除和编辑员工,我们增强该页面的功能。这样这个程序就更实用了。
先添加删除功能:
将sqldsClerkList配置里面添加启用insert,delete和update,
在clerkGridView中启用删除,并编辑RowDeleteing 事件:











这里能够删除是因为 clerkgridView有DataKeyNames="ClerkID" 这个属性
而sqldsClerkList有这个命令DeleteCommand="DELETE FROM [Clerk] WHERE [ClerkID] = @original_ClerkID"
如果DataKey是多重字段组合的,该怎么办呢?比如没有员工ID,只能根据员工姓名和部门来唯一确定员工,那么gridview指定的关键字段就是一个集合了:





要是我们要求在编辑模式下不能选择其他行,应该怎么办呢?
答案是在选择行的事件上判断当前是否是编辑模式,如果是就选定行。代码如下:












用gridview来编辑记录其实并不实用,很多情况下,表格比较复杂,字段比较多,有些字段还需要限制输入,这时候就必须使用到DataList,Repeater或者是DetailsView,FormView等控件了。其中用的最多的就是FormView,因为它是完全模板搭建的,有更强的自定义表单功能,就利用他来实现员工信息编辑吧。
看看以前学习的历史,无不是使用拖放控件,绑定数据源,偶尔加点自定义模板,和事件处理代码,虽然编码量很少,但是总觉得不能随心所欲,而且看到clerklist.aspx的源码,充满了系统生成的对各个控件的参数,前台页面不够简洁。而却比如要实现以下的界面,单单靠几个拖放,总不能完全实现,而且对于数据源控件的一点点改动都会导致相应绑定的显示控件的刷新和一些架构的丢失,然后再运行页面就可能出错了,总不如自己写后台代码来的可靠。那么我们就以下面的界面为目标,真正掌握Asp.NET2.0中ADO.NET的代码编写吧!