首先,您需要通过右键单击“解决方案资源管理器”选项卡中的根文件来创建一个 .vb 文件/类(我使用 VWD)。选择添加新的并选择类页面。它将提供创建共享类所在的 App_Code 文件夹。将文件/类命名为“DeleteButtonField.vb”,然后单击“确定”。
然后它应该会打开一个名为 DeleteButtonField 的新 .vb 文件,您可以复制和粘贴或输入以下代码。 (请注意,您可以使用 Intellisense 来完成定义 Protected Overrides Sub InitializeCell(........) 的那段非常长的代码。)
Imports Microsoft.VisualBasic
Imports System
Imports System.Web.UI.WebControls
Namespace myControls
Public Class DeleteButtonField
Inherits ButtonField
Private _confirmText As String = "Delete This Record?"
Public Property ConfirmText() As String
Get
Return _confirmText
End Get
Set(ByVal value As String)
_confirmText = value
End Set
End Property
Public Sub New()
Me.CommandName = "Delete"
Me.Text = "Delete"
End Sub
Public Overrides Sub InitializeCell(ByVal cell As System.Web.UI.WebControls.DataControlFieldCell, ByVal cellType As System.Web.UI.WebControl.DataControlCellType, ByVal rowState As System.Web.UI.WebControl.DataControlRowState, ByVal rowIndex As Integer)
MyBase.InitializeCell(cell, cellType, rowState, rowIndex)
If cellType = DataControlCellType.DataCell Then
Dim button As WebControl = CType(cell.Controls(0), WebControl)
button.Attributes("onclick") = String.Format("return confirm('{0}');", _confirmText)
End If
End Sub
End Class
End Namespace
保存 .vb 文件。然后在您的 .aspx 页面中,以源代码模式打开页面并找到您的 GridView 定义(即标签。您可以选择希望删除按钮出现的位置,第一个位置,第二个等。确保选择一个文本位置,这样您就不会更改任何定义,并添加以下内容
<custom:DeleteButtonField ConfirmText="Are you sure that you want to delete this record?"></custom:DeleteButtonField>
您还需要在页面顶部的之后添加一行,如下所示
<%@ Register TagPrefix="custom" Namespace="myControls" %>
这也需要添加到您打算在 GridView 中使用新删除按钮的每个页面上。可能有一种方法可以在 web.config 中将其设置为默认值;在我学习的这个阶段,我不在那里。
保存您的 .aspx 页面并进行测试。您现在已经定义了一个通用的 Sub(它定义了一个标准的 Delete 按钮及其行为),您可以将其附加到应用程序中的任何 GridView。