(Add edit delete update records in Gridview) – Đối với những bảng dữ liệu có ít cột, người lập trình có thể xây dựng chức năng: Thêm, sửa dữ liệu ngay tại Gridview. Với cách xây dựng này sẽ giúp người sử dụng dễ dàng và nhanh chóng thao tác với dữ liệu khi cần. Bài viết dưới đây sẽ hướng dẫn các bạn thực hiện công việc này.

Nghe những bài hát đỉnh nhất về Thấy cô giáo - Nghe trên Youtube



Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



B1: Tạo CSDL Customers trong SQL Server

B2: Tạo Bảng Accounts có cấu trúc phía dưới

STTTên trườngKiểu trườngGhi chú
1AccountIDIntTrường tự tăng
2AccountCodenvarchar(25)
3AccNamenvarchar(250)
4AccAddressnvarchar(250)
5AccPhonenvarchar(50)
6AccFAXnvarchar(50)
7AccEmailnvarchar(50)
8AccWebsitenvarchar(150)
9AccDescnvarchar(1500)
10CreatedDatedatetime
11ModifiedDatedatetime


B3: Nhập dữ liệu cho bảng Accounts


B4: Tạo các stored procedure trong SQL Server

CREATE PROCEDURE [dbo].[Pro_Accounts_Add]
      @AccountCode nvarchar(25)
      ,@AccName nvarchar(250)
      ,@AccAddress nvarchar(250)
      ,@AccPhone nvarchar(80)
      ,@AccFAX nvarchar(50)
      ,@AccEmail nvarchar(500)
      ,@AccWebsite nvarchar(150)
      ,@AccDesc nvarchar(2000)
AS

INSERT INTO Accounts (
      [AccountCode]
      ,[AccName]
      ,[AccAddress]
      ,[AccPhone]
      ,[AccFAX]
      ,[AccEmail]
      ,[AccWebsite]
      ,[AccDesc]
      ,[CreatedDate]
      ,[ModifiedDate]
     
) VALUES (
      @AccountCode
      ,@AccName
      ,@AccAddress
      ,@AccPhone
      ,@AccFAX
      ,@AccEmail
      ,@AccWebsite
      ,@AccDesc
      ,getdate()
      ,getdate() 
)
select SCOPE_IDENTITY()
Go

CREATE PROCEDURE [dbo].[Pro_Accounts_Update]
      @AccountID int,
      @AccountCode nvarchar(25),
      @AccName nvarchar(250),
      @AccAddress nvarchar(250),
      @AccPhone nvarchar(80),
      @AccFAX nvarchar(50),
      @AccEmail nvarchar(500),
      @AccWebsite nvarchar(150),
      @AccDesc nvarchar(2000)
AS

UPDATE Accounts SET
   [AccountCode] =@AccountCode
   ,[AccName] = @AccName
   ,[AccAddress] = @AccAddress
   ,[AccPhone] = @AccPhone
   ,[AccFAX] = @AccFAX
   ,[AccEmail] = @AccEmail
   ,[AccWebsite] = @AccWebsite
   ,[AccDesc] = @AccDesc        
   ,[ModifiedDate] = getdate()
WHERE
    [AccountID] =@AccountID
Go

CREATE PROCEDURE [dbo].[Pro_Accounts_List]
      @Keyword nvarchar(250),
      @SortField nvarchar(50),
      @SortType nvarchar(10)
AS

declare@strSQL   nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)

set @strSQL= 'Select * from Accounts'
set @strWhere =' Where 1=1 '

if @Keyword<>''
      set @strWhere= @strWhere  +' And (AccountCode like N''%' +@Keyword+'%''
            Or AccName like N''%' +@Keyword+'%'' Or AccAddress like N''%' +@Keyword+'%''
            Or AccPhone like N''%' +@Keyword+'%'' Or AccFAX like N''%' +@Keyword+'%''
            Or AccEmail like N''%' +@Keyword+'%'' Or AccWebsite like N''%' +@Keyword+'%'')'

if @SortField='CreatedDate'
      Begin
            set @strOrder =' Order by CreatedDate'
      End
Else
      Begin
            set @strOrder =' Order by AccName'
      End

set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql @strSQL
GO

CREATE PROCEDURE [dbo].[Pro_Accounts_Delete]
      @ItemID int
AS
DELETE FROM Accounts
WHERE AccountID = @ItemID

Go

Bạn có thể tải về bảng cơ sở dữ liệu SQL bằng cách nhấn vào liên kết tải về dưới đây

B5: Tạo Project trong Microsoft Visual Studio 2010

Trong Visual Studio tạo 1 Class có tên: Utility và nhập đoạn Code phía dưới cho Class này.

Imports System.Data.SqlClient
Imports System.Data

Namespace InsertUpdateDeleteRecords

    Public Class SqlDataProvider

#Region "Membres Prives"

        Shared _IsError As Boolean = False
        Private _connectionString AsString

#End Region

#Region "Constructeurs"

        Public Sub New()
            Try
                _connectionString = ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString
                _IsError = False
            Catch ex As Exception
                _IsError = True
            End Try
        End Sub

#End Region

#Region "Proprietes"

        Public ReadOnly Property ConnectionString() AsString
            Get
                Return _connectionString
            End Get
        End Property

#End Region

#Region "Functions"

        Public FunctionFillTable(ByVal sql AsString) As DataTable
            Try
                Dim tb AsNew DataTable
                Dim adap AsNew SqlDataAdapter(sql, _connectionString)
                adap.Fill(tb)
                Return tb
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Public FunctionFillTable(ByVal ProcName As String, ByVal ParamArrayPara() As ObjectPara) As DataTable
            Try
                Dim tb AsNew DataTable
                Dim adap AsNew SqlDataAdapter(ProcName, _connectionString)
                adap.SelectCommand.CommandType = CommandType.StoredProcedure
                If NotPara Is NothingThen
                    For Eachp As ObjectParaIn Para
                        adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
                    Next
                End If
                adap.Fill(tb)
                Return tb
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Public FunctionRunSQL(ByVal ProcName AsString, ByVal ParamArray Para() As ObjectPara) As Integer
            Dim iExecute As Integer = 0
            Try
                Dim _cnn AsNew SqlConnection(_connectionString)
                _cnn.Open()

                Dim cmd AsNew SqlCommand(ProcName, _cnn)
                cmd.CommandType = CommandType.StoredProcedure
                For Eachp As ObjectParaIn Para
                    cmd.Parameters.Add(New SqlParameter(p.Name, p.Value))
                Next
                'cmd.ExecuteScalar()
                iExecute = cmd.ExecuteNonQuery()
            Catch ex As Exception

            End Try
            Return iExecute
        End Function

        Public FunctionGetRow(ByVal ProcName AsString, ByVal ParamArray Para() As ObjectPara) As DataRow
            Try
                Dim tb AsNew DataTable
                Dim adap AsNew SqlDataAdapter(ProcName, _connectionString)
                adap.SelectCommand.CommandType = CommandType.StoredProcedure
                For Eachp As ObjectParaIn Para
                    adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
                Next
                adap.Fill(tb)
                If tb.Rows.Count Then
                    Return tb.Rows(0)
                End If
            Catch ex As Exception
                Return Nothing
            End Try
            Return Nothing
        End Function

#End Region

    End Class

    Public Class ObjectPara
        Dim _name As String
        Dim _Value As Object

        Sub New(ByVal Pname As String, ByVal PValue As Object)
            _name = Pname
            _Value = PValue
        End Sub

        Public PropertyName() As String
            Get
                Return _name
            End Get
            Set(ByVal value As String)
                _name = value
            End Set
        End Property

        Public PropertyValue() As Object
            Get
                Return _Value
            End Get
            Set(ByVal value As Object)
                _Value = value
            End Set
        End Property

    End Class

End Namespace

Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config

B6: Download thư viện AjaxControlToolkit tại địa chỉ: Download

B7: Giải nén AjaxControlToolkit.Binary.NET4, và References Ajaxcontroltoolkit.dll trong thư mục vừa giải nén vào Project.

- B8: Download các file ảnh tại đây và Copy các file này vào thư mục Images của Project.

B9: Mở file Site.css nhập thêm đoạn Code phía dưới
.NormalRed
{
    font-familyTahoma, Arial, Helvetica;
    font-size12px;
    font-weightbold;
    color#ff0000;
}

B10: Mở file Default.aspxdưới dạng HTML và  bổ xung Control

<%@ PageTitle="How to add edit delete update records in Gridview ASP.NET" Language="vb"MasterPageFile="~/Site.Master"AutoEventWireup="false"EnableEventValidation="false" CodeBehind="Default.aspx.vb" Inherits="InsertUpdateDeleteRecords._Default" %>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1"EnablePageMethods ="true" runat="server">
    </asp:ScriptManager>
    <h3>
        How to add edit delete update records in Gridview ASP.NET
    </h3>
    <br />
    <asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="2"cellspacing="3"width="100%">
                <tr>
                    <td>
                    </td>
                    <tdalign="right">
                        <asp:Label ID="plKeyword" runat="server" Text="Keyword"></asp:Label>
                        <asp:TextBox ID="txtSearch" CssClass="form-control" ToolTip="Enter Keyword" runat="server" width="200px"></asp:TextBox>
                        <asp:ImageButton ID="cmdQuickSearch" runat="server" causesvalidation="false" imageurl="~/images/icon_search.gif"></asp:ImageButton>
                    </td>
                </tr>
                <trid="trMessage"runat="server"visible="false">
                    <tdcolspan="2">
                        <asp:Label ID="lblMessage" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <tdcolspan="2">
                       <asp:GridView ID="grvObject" runat="server" AllowPaging="true" PageSize="8" ShowFooter="true"
                            CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"
                            BorderWidth="1"AutoGenerateColumns="false"DataKeyNames="AccountID"width="100%">
                            <AlternatingRowStyleCssClass="GridStyle_AltRowStyle"/>
                            <HeaderStyle CssClass="GridStyle_HeaderStyle"/>
                            <RowStyle CssClass="GridStyle_RowStyle"/>
                            <FooterStyle CssClass="GridStyle_FooterStyle"/>
                            <pagerstyle cssclass="GridStyle_pagination"/>
                            <Columns>
                                <asp:TemplateField HeaderText="AccountCode">
                                    <ItemStyle Width="6%"></ItemStyle>
                                    <ItemTemplate>
                                        <asp:Label ID="lblAccountCode"runat="server"Text='<%#Eval("AccountCode") %>'></asp:Label>
                                    </ItemTemplate>
                                    <EditItemTemplate>   
                                        <asp:Label ID="lblAccountID"Visible="false"runat="server"Text='<%#Eval("AccountID") %>'></asp:Label>      
                                        <asp:TextBox ID="txtAccountCode"Width="80"runat="server"Text='<%#Eval("AccountCode") %>'></asp:TextBox>      
                                    </EditItemTemplate>
                                    <FooterTemplate>
                                        <asp:TextBox ID="txtAccountCode_Add"Width="80"runat="server"></asp:TextBox>
                                        <asp:RequiredFieldValidatorID="valAccountCode"runat="server"CssClass="NormalRed"ValidationGroup="Add"ControlToValidate="txtAccountCode_Add"ErrorMessage="Enter Code" Display="dynamic"></asp:RequiredFieldValidator>
                                    </FooterTemplate>
                                </asp:TemplateField>
                               
                                <asp:TemplateField HeaderText="AccountName">
                                    <ItemStyle Width="18%"></ItemStyle>
                                    <ItemTemplate>
                                        <asp:Label ID="lblAccountName"runat="server"Text='<%#Eval("AccName") %>'></asp:Label>
                                    </ItemTemplate>
                                    <EditItemTemplate>          
                                        <asp:TextBox ID="txtAccountName"runat="server"Text='<%#Eval("AccName") %>'></asp:TextBox>      
                                    </EditItemTemplate>
                                    <FooterTemplate>
                                        <asp:TextBox ID="txtAccountName_Add"runat="server"></asp:TextBox>
                                        <asp:RequiredFieldValidatorID="valAccountName"runat="server"CssClass="NormalRed"ValidationGroup="Add"ControlToValidate="txtAccountName_Add"ErrorMessage="Enter Name" Display="dynamic"></asp:RequiredFieldValidator>
                                    </FooterTemplate>
                                </asp:TemplateField>

                                <asp:TemplateField HeaderText="Phone">
                                    <ItemStyle Width="8%"></ItemStyle>
                                    <ItemTemplate>
                                        <asp:Label ID="lblAccPhone"runat="server"Text='<%#Eval("AccPhone") %>'></asp:Label>
                                    </ItemTemplate>
                                    <EditItemTemplate>          
                                        <asp:TextBox ID="txtPhone"Width="100"runat="server"Text='<%#Eval("AccPhone") %>'></asp:TextBox>      
                                    </EditItemTemplate>
                                    <FooterTemplate>
                                        <asp:TextBox ID="txtPhone_Add"Width="100"runat="server"></asp:TextBox>
                                    </FooterTemplate>
                                </asp:TemplateField>

                                <asp:TemplateField HeaderText="Fax">
                                    <ItemStyle Width="10%"></ItemStyle>
                                    <ItemTemplate>
                                        <asp:Label ID="lblAccFAX"runat="server"Text='<%#Eval("AccFAX") %>'></asp:Label>
                                    </ItemTemplate>
                                    <EditItemTemplate>          
                                        <asp:TextBox ID="txtFAX" Width="100" runat="server"Text='<%#Eval("AccFAX") %>'></asp:TextBox>       
                                    </EditItemTemplate>
                                    <FooterTemplate>
                                        <asp:TextBox ID="txtFAX_Add"Width="100"runat="server"></asp:TextBox>
                                    </FooterTemplate>
                                </asp:TemplateField>

                                <asp:TemplateField HeaderText="Email">
                                    <ItemStyle Width="10%"></ItemStyle>
                                    <ItemTemplate>
                                        <asp:Label ID="lblAccEmail"runat="server"Text='<%#Eval("AccEmail") %>'></asp:Label>
                                    </ItemTemplate>
                                    <EditItemTemplate>          
                                        <asp:TextBox ID="txtEmail"runat="server"Text='<%#Eval("AccEmail") %>'></asp:TextBox>      
                                    </EditItemTemplate>
                                    <FooterTemplate>
                                        <asp:TextBox ID="txtEmail_Add"runat="server"></asp:TextBox>
                                    </FooterTemplate>
                                </asp:TemplateField>

                                <asp:TemplateField HeaderText="Website">
                                    <ItemStyle Width="10%"></ItemStyle>
                                    <ItemTemplate>
                                        <asp:Label ID="lblAccWebsite"runat="server"Text='<%#Eval("AccWebsite") %>'></asp:Label>
                                    </ItemTemplate>
                                    <EditItemTemplate>          
                                        <asp:TextBox ID="txtWebsite"runat="server"Text='<%#Eval("AccWebsite") %>'></asp:TextBox>      
                                    </EditItemTemplate>
                                    <FooterTemplate>
                                        <asp:TextBox ID="txtWebsite_Add"runat="server"></asp:TextBox>
                                    </FooterTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField>
                                    <ItemStyle HorizontalAlign="Center"width="3%"/>
                                    <ItemTemplate>
                                        <asp:ImageButton ID="cmdEdit"CommandName="Edit"CommandArgument='<%# Eval("AccountID")%>' runat="server"ImageUrl="~/images/edit.gif"CausesValidation="False"></asp:ImageButton>
                                        <asp:ImageButton ID="cmdDelete"CommandName="Delete"CommandArgument='<%# Eval("AccountID")%>' runat="server"ImageUrl="~/images/delete.gif"CausesValidation="False"></asp:ImageButton>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                       <asp:ImageButton ID="cmdUpdate"runat="server"CommandName="Update"ToolTip="Update"ImageUrl="~/Images/save.gif"/>
                                       <asp:ImageButton ID="cmdCancel"runat="server"CommandName="Cancel"ToolTip="Cancel"ImageUrl="~/Images/cancel.gif"/>
                                    </EditItemTemplate>
                                    <FooterTemplate>
                                       <asp:LinkButton ID="cmdAdd" runat="server"ValidationGroup="Add"CommandName="Add"Text="Add"ImageUrl="~/Images/add.gif"Width="100px"></asp:LinkButton>
                                    </FooterTemplate>
                                </asp:TemplateField>                         
                            </Columns>                              
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

B11: Viết Code cho file Default.aspx

Imports System.Data

Namespace InsertUpdateDeleteRecords

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Private Methods"

        Private SubDeleteAccount(ByVal ItemID As Integer)
            Dim objSQL As New SqlDataProvider
            objSQL.RunSQL("Pro_Accounts_Delete", New ObjectPara("@ItemID", ItemID))
            BindAccount()
        End Sub

        Private FunctionEditAccount(ByVal ItemID As Integer, ByVal AccountCode As String, ByVal AccName As String, ByVal AccPhone As String, ByVal AccFAX As String, _
                               ByVal AccWebsite As String, ByValAccEmail As String, ByVal Command AsString) As Integer
            Dim objSQL As New SqlDataProvider
            Dim iError As Integer = -1

            If Command = "Edit"Then
                iError = objSQL.RunSQL("Pro_Accounts_Update", New ObjectPara("@AccountID", ItemID), _
                                               New ObjectPara("@AccountCode", AccountCode), _
                                               New ObjectPara("@AccName", AccName), _
                                               New ObjectPara("@AccAddress", ""), _
                                               New ObjectPara("@AccPhone", AccPhone), _
                                               New ObjectPara("@AccFAX", AccFAX), _
                                               New ObjectPara("@AccEmail", AccEmail), _
                                               New ObjectPara("@AccWebsite", AccWebsite), _
                                               New ObjectPara("@AccDesc", ""))
            Else
                iError = objSQL.RunSQL("Pro_Accounts_Add", New ObjectPara("@AccountCode", AccountCode), _
                                               New ObjectPara("@AccName", AccName), _
                                               New ObjectPara("@AccAddress", ""), _
                                               New ObjectPara("@AccPhone", AccPhone), _
                                               New ObjectPara("@AccFAX", AccFAX), _
                                               New ObjectPara("@AccEmail", AccEmail), _
                                               New ObjectPara("@AccWebsite", AccWebsite), _
                                               New ObjectPara("@AccDesc", ""))
            End If
            Return iError
        End Function

#End Region

#Region "Bind Data"

        Private SubBindAccount()
            Dim objBind As New DataTable
            objBind = BindData(txtSearch.Text)

            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then
                    grvObject.DataSource = objBind
                    grvObject.DataBind()
                    trMessage.Visible = False
                    grvObject.Visible = True
                Else
                    trMessage.Visible = True
                    grvObject.Visible = False
                    lblMessage.Text = "No Data"
                End If
                updatePanel.Update()
            End If
        End Sub

        Public Shared Function BindData(ByValKeyword As String) As DataTable
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable("Pro_Accounts_List", New ObjectPara("@Keyword", Keyword.Trim), _
                                                                          New ObjectPara("@SortField", "CreatedDate"), _
                                                                          New ObjectPara("@SortType", "DESC"))
            Return objBind
        End Function

#End Region

#Region "GridView Methods"

        Private SubgrvObject_RowCommand(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewCommandEventArgs) Handles grvObject.RowCommand
            If e.CommandName = "Add"Then
                With grvObject
                    Dim IsAdded AsBoolean = False
                    Dim AccountName AsString = ""
                    Dim txtAccountCode As TextBox = DirectCast(.FooterRow.FindControl("txtAccountCode_Add"), TextBox)
                    Dim txtAccName AsTextBox = DirectCast(.FooterRow.FindControl("txtAccountName_Add"), TextBox)
                    Dim txtAccPhone AsTextBox = DirectCast(.FooterRow.FindControl("txtPhone_Add"), TextBox)
                    Dim txtFax AsTextBox = DirectCast(.FooterRow.FindControl("txtFAX_Add"), TextBox)
                    Dim txtWebsite AsTextBox = DirectCast(.FooterRow.FindControl("txtWebsite_Add"), TextBox)
                    Dim txtEmail AsTextBox = DirectCast(.FooterRow.FindControl("txtEmail_Add"), TextBox)

                    If NottxtAccName Is NothingAnd txtAccName.Text <> "" Then
                        AccountName = txtAccName.Text
                    End If

                    If NottxtAccountCode Is NothingAnd NottxtAccName Is NothingAnd NottxtAccPhone Is Nothing_
                    And NottxtFax Is NothingAnd NottxtWebsite Is NothingAnd NottxtEmail Is NothingThen
                        IsAdded = EditAccount(-1, txtAccountCode.Text, txtAccName.Text, txtAccPhone.Text, txtFax.Text, txtWebsite.Text, txtEmail.Text, "Add") > 0
                    End If

                    IfIsAdded Then
                        lblMessage.Text = AccountName & " has been added successfully!"
                        lblMessage.ForeColor = System.Drawing.Color.Green
                        BindAccount()
                    Else
                        lblMessage.Text = "Error while adding: " & AccountName
                        lblMessage.ForeColor = System.Drawing.Color.Red
                    End If
                    trMessage.Visible = True
                End With
            End If
        End Sub

        Private SubgrvObject_RowUpdating(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewUpdateEventArgs) Handles grvObject.RowUpdating
            With grvObject
                Dim ItemID AsInteger = -1
                Dim lblAccountID As Label = DirectCast(.Rows(e.RowIndex).FindControl("lblAccountID"), Label)
                Dim txtAccountCode As TextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtAccountCode"), TextBox)
                Dim txtAccName AsTextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtAccountName"), TextBox)
                Dim txtAccPhone AsTextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtPhone"), TextBox)
                Dim txtFax AsTextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtFAX"), TextBox)
                Dim txtWebsite AsTextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtWebsite"), TextBox)
                Dim txtEmail AsTextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtEmail"), TextBox)

                If NotlblAccountID Is NothingAnd lblAccountID.Text <> "" Then
                    ItemID = lblAccountID.Text
                End If

                If NottxtAccountCode Is NothingAnd NottxtAccName Is NothingAnd NottxtAccPhone Is Nothing_
                    And NottxtFax Is NothingAnd NottxtWebsite Is NothingAnd NottxtEmail Is NothingThen
                    EditAccount(ItemID, txtAccountCode.Text, txtAccName.Text, txtAccPhone.Text, txtFax.Text, txtWebsite.Text, txtEmail.Text, "Edit")
                    grvObject.EditIndex = -1
                    BindAccount()
                End If
            End With
        End Sub

        Private SubgrvObject_RowDataBound(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewRowEventArgs) Handles grvObject.RowDataBound
            If (e.Row.RowType = DataControlRowType.DataRow) Then
                Dim cmdDelete AsImageButton = CType(e.Row.FindControl("cmdDelete"), ImageButton)
                If cmdDelete IsNotNothing Then
                    cmdDelete.Attributes.Add("onClick", "javascript:return confirm('"& "Are you sure you want to delete?"& "');")
                    cmdDelete.ToolTip = "Delete Account"
                End If
            End If
        End Sub

        Private SubgrvObject_RowDeleting(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewDeleteEventArgs) Handles grvObject.RowDeleting
            Dim ItemID As Integer = CType(grvObject.DataKeys(e.RowIndex).Value, Integer)
            If ItemID <> -1 Then
                DeleteAccount(ItemID)
            End If
        End Sub

        Private SubgrvObject_RowCancelingEdit(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles grvObject.RowCancelingEdit
            grvObject.EditIndex = -1
            BindAccount()
        End Sub

        Private SubgrvObject_RowEditing(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewEditEventArgs) Handles grvObject.RowEditing
            grvObject.EditIndex = e.NewEditIndex
            BindAccount()
        End Sub

        Private Sub grvObject_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grvObject.PageIndexChanging
            grvObject.PageIndex = e.NewPageIndex
            BindAccount()
        End Sub

#End Region

#Region "Event Handles"

        Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
            Try
                If Page.IsPostBack = False Then
                    'Default Submit Button
                    Page.Form.DefaultButton = cmdQuickSearch.UniqueID
                    BindAccount()
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private SubcmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdQuickSearch.Click
            BindAccount()
        End Sub

#End Region

    End Class

End Namespace

Bây giờ chạy Project bạn sẽ có kết quả như ảnh phía dưới.

Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



Chúc các bạn thành công!

Quang Bình

0 comments Blogger 0 Facebook

Post a Comment

 
lập trình đốt nét © 2013. All Rights Reserved. Powered by Blogger
Top