程序代码说明
GridView 的 CommandField 因为切换为 TemplateField,所以在 RowDataBound 事件中,需要去设定「编辑」钮的 CommandArgument 属性值为 RowIndex,GridView 的编辑动作才能正常执行。
1 Protected Sub GridView1_RowDataBound()Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
2 Dim oButton As Button
3
4 If e.Row.RowType = DataControlRowType.DataRow Then
5 '设定编辑钮的 CommandArgument
6 oButton = CType(e.Row.Cells(0).FindControl("btnEdit"), Button)
7 oButton.CommandArgument = e.Row.RowIndex.ToString
8 End If
9 End Sub
程序执行时预设为浏览模式,故只有显示 GridView,而 FormView 预设是隐藏。当 GridView 按下新增及编辑时,需要将 GirdView 隐藏,将 FormView 显示。所以在 GridView 的 RowCommand 事件中撰写如下程序代码。
执行「编辑」时,以 GetEditIndex 函式是取得 FormView 对应的编辑列索引,设定给 FormView.PageIndex,并将 FormView 切换为编辑模式。
执行「新增」钮,将 FormView.InsertItemTemplate 设为 FormView.EddiItemTemplate,即新增及编辑都使用同一个 Template,并将 FormView 切换为新增模式。
1 Protected Sub GridView1_RowCommand()Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
2 Dim iEditIndex As Integer
3
4 Select Case e.CommandName.ToUpper
5 Case "Edit".ToUpper '编辑模式
6 iEditIndex = GetEditIndex(CType(sender, GridView), CInt(e.CommandArgument))
7 FormView1.PageIndex = iEditIndex
8 FormView1.ChangeMode(FormViewMode.Edit) 'FormView 切换为编辑模式
9 FormView1.Visible = True 'FormView 显示
10 GridView1.Visible = False 'GridView 隐藏
11
12 Case "Insert".ToUpper '新增模式
13 '因为只有使用 EditItemTemplate,故将 InsertItemTemplate 设为 EditItemTemplate
14 FormView1.InsertItemTemplate = FormView1.EditItemTemplate
15 FormView1.ChangeMode(FormViewMode.Insert) 'FormView 切换为新增模式
16 FormView1.Visible = True 'FormView 显示
17 GridView1.Visible = False 'GridView 隐藏
18 End Select
19 End Sub
20
21 /**/''' <summary>
22 ''' 取得编辑列索引。
23 ''' </summary>
24 ''' <param name="GridView">GridView 控件。</param>
25 ''' <param name="RowIndex">GridView 的数据列索引。</param>
26 Private Function GetEditIndex()Function GetEditIndex(ByVal GridView As GridView, ByVal RowIndex As Integer) As Integer
27 Dim iEditIndex As Integer
28
29 If GridView.AllowPaging Then
30 'GridView 有分页时,要把考虑目前的页数及每页笔数
31 iEditIndex = (GridView.PageIndex) * GridView.PageSize + RowIndex
32 Else
33 'GridView 无分页时,直接使用 e.NewSelectedIndex
34 iEditIndex = RowIndex
35 End If
36 Return iEditIndex
37 End Function
在 FormView 中因为只使用 EddiItemTemplate 来处理「新增」及「编辑」模式,做需要置放「新增」、「更新」、「取消」三个按钮。
在「新增」模式显示「新增」钮与「取消」钮,以及显示 EmployeeID 字段的 TextBox。
在「编辑」模式显示「更新」钮与「取消」钮。EmployeeID 字段为只读,故隐藏 EmployeeID 字段的 TextBox。
针对以上的处理动作,在 FormView 的 PreRender 事件中撰写如下程序代码来处理 FormView 子控件的显示及隐藏状态。
RSS订阅






收 藏
推 荐