News Ticker

Menu

Thêm, sửa, xóa dữ liệu trong GridView trong Asp.net

(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.

Xem những Video hay dành cho thiếu nhi - Xem 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 As String

#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() As String
            Get
                Return _connectionString
            End Get
        End Property

#End Region

#Region "Functions"

        Public Function FillTable(ByVal sql As String) As DataTable
            Try
                Dim tb As New DataTable
                Dim adap As New SqlDataAdapter(sql, _connectionString)
                adap.Fill(tb)
                Return tb
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Public Function FillTable(ByVal ProcName As String, ByVal ParamArray Para() As ObjectPara) As DataTable
            Try
                Dim tb As New DataTable
                Dim adap As New SqlDataAdapter(ProcName, _connectionString)
                adap.SelectCommand.CommandType = CommandType.StoredProcedure
                If Not Para Is Nothing Then
                    For Each p As ObjectPara In 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 Function RunSQL(ByVal ProcName As String, ByVal ParamArray Para() As ObjectPara) As Integer
            Dim iExecute As Integer = 0
            Try
                Dim _cnn As New SqlConnection(_connectionString)
                _cnn.Open()

                Dim cmd As New SqlCommand(ProcName, _cnn)
                cmd.CommandType = CommandType.StoredProcedure
                For Each p As ObjectPara In 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 Function GetRow(ByVal ProcName As String, ByVal ParamArray Para() As ObjectPara) As DataRow
            Try
                Dim tb As New DataTable
                Dim adap As New SqlDataAdapter(ProcName, _connectionString)
                adap.SelectCommand.CommandType = CommandType.StoredProcedure
                For Each p As ObjectPara In 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 Property Name() As String
            Get
                Return _name
            End Get
            Set(ByVal value As String)
                _name = value
            End Set
        End Property

        Public Property Value() 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

<%@ Page Title="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>
                    <td align="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>
                <tr id="trMessage" runat="server" visible="false">
                    <td colspan="2">
                        <asp:Label ID="lblMessage" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td colspan="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%">
                            <AlternatingRowStyle CssClass="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:RequiredFieldValidator ID="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:RequiredFieldValidator ID="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 Sub DeleteAccount(ByVal ItemID As Integer)
            Dim objSQL As New SqlDataProvider
            objSQL.RunSQL("Pro_Accounts_Delete", New ObjectPara("@ItemID", ItemID))
            BindAccount()
        End Sub

        Private Function EditAccount(ByVal ItemID As Integer, ByVal AccountCode As String, ByVal AccName As String, ByVal AccPhone As String, ByVal AccFAX As String, _
                               ByVal AccWebsite As String, ByVal AccEmail As String, ByVal Command As String) 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 Sub BindAccount()
            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(ByVal Keyword 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 Sub grvObject_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grvObject.RowCommand
            If e.CommandName = "Add" Then
                With grvObject
                    Dim IsAdded As Boolean = False
                    Dim AccountName As String = ""
                    Dim txtAccountCode As TextBox = DirectCast(.FooterRow.FindControl("txtAccountCode_Add"), TextBox)
                    Dim txtAccName As TextBox = DirectCast(.FooterRow.FindControl("txtAccountName_Add"), TextBox)
                    Dim txtAccPhone As TextBox = DirectCast(.FooterRow.FindControl("txtPhone_Add"), TextBox)
                    Dim txtFax As TextBox = DirectCast(.FooterRow.FindControl("txtFAX_Add"), TextBox)
                    Dim txtWebsite As TextBox = DirectCast(.FooterRow.FindControl("txtWebsite_Add"), TextBox)
                    Dim txtEmail As TextBox = DirectCast(.FooterRow.FindControl("txtEmail_Add"), TextBox)

                    If Not txtAccName Is Nothing And txtAccName.Text <> "" Then
                        AccountName = txtAccName.Text
                    End If

                    If Not txtAccountCode Is Nothing And Not txtAccName Is Nothing And Not txtAccPhone Is Nothing _
                    And Not txtFax Is Nothing And Not txtWebsite Is Nothing And Not txtEmail Is Nothing Then
                        IsAdded = EditAccount(-1, txtAccountCode.Text, txtAccName.Text, txtAccPhone.Text, txtFax.Text, txtWebsite.Text, txtEmail.Text, "Add") > 0
                    End If

                    If IsAdded 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 Sub grvObject_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles grvObject.RowUpdating
            With grvObject
                Dim ItemID As Integer = -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 As TextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtAccountName"), TextBox)
                Dim txtAccPhone As TextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtPhone"), TextBox)
                Dim txtFax As TextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtFAX"), TextBox)
                Dim txtWebsite As TextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtWebsite"), TextBox)
                Dim txtEmail As TextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtEmail"), TextBox)

                If Not lblAccountID Is Nothing And lblAccountID.Text <> "" Then
                    ItemID = lblAccountID.Text
                End If

                If Not txtAccountCode Is Nothing And Not txtAccName Is Nothing And Not txtAccPhone Is Nothing _
                    And Not txtFax Is Nothing And Not txtWebsite Is Nothing And Not txtEmail Is Nothing Then
                    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 Sub grvObject_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grvObject.RowDataBound
            If (e.Row.RowType = DataControlRowType.DataRow) Then
                Dim cmdDelete As ImageButton = CType(e.Row.FindControl("cmdDelete"), ImageButton)
                If cmdDelete IsNot Nothing 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 Sub grvObject_RowDeleting(ByVal sender As Object, ByVal e As System.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 Sub grvObject_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles grvObject.RowCancelingEdit
            grvObject.EditIndex = -1
            BindAccount()
        End Sub

        Private Sub grvObject_RowEditing(ByVal sender As Object, ByVal e As System.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 Sub Page_Load(ByVal sender As Object, 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 Sub cmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdQuickSearch.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

Share This:

Post Tags:

Mỗi bài viết đều là công sức và thời gian của tác giả ví vậy tác giả chỉ có một mong muốn duy nhất nếu ai đó có Copy thì xin hãy ghi rõ nguồn và thông tin tác giả ở cuối mỗi bài viết.
Xin cảm ơn!

No Comment to " Thêm, sửa, xóa dữ liệu trong GridView trong Asp.net "

  • To add an Emoticons Show Icons
  • To add code Use [pre]code here[/pre]
  • To add an Image Use [img]IMAGE-URL-HERE[/img]
  • To add Youtube video just paste a video link like http://www.youtube.com/watch?v=0x_gnfpL3RM