How can I customize automatically generated command button, e.g. Delete
?
I want to add a client confirmation on deleting and in the same moment I want this
First, you need to create a .vb file/class by rightclicking on your root file in the Solutions Explorer tab (I use VWD). Select Add New and choose Class page. It will offer to create the App_Code folder which is where your shared classes will reside. Name the file/class as "DeleteButtonField.vb" and click OK.
It should then open a new .vb file called DeleteButtonField and you can copy and paste or enter the code below. (Note that you can use Intellisense to complete the really long bit of code that defines the 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
Save the .vb file. Then in your .aspx page, open up the page in source mode and find your GridView definition (i.e. tags. You can choose where you want the Delete button to appear, either the first position, second or so on. Make sure that you choose a text position so that you don't change any of the definitions, and add the following
You also need to add a line at the top of your page after the <%@ Page ...> as follows
<%@ Register TagPrefix="custom" Namespace="myControls" %>
This also needs to be added on every page where you intend using the new Delete Button in a GridView. There may be a way to set this up as a default in web.config; I'm not there at this stage of my learning.
Save your .aspx page and test. You have now defined a common Sub (which defines a standard Delete button and its behaviour) that you can attach to any GridView in your application.