News Ticker

Menu

Cập nhật đồng loạt nhiều giá trị vào Database trên Gridview

(Thay đổi động loạt nhiều giá trị từ Checkbox trên Gridview) –  Trên Gridview là danh sách các sản phẩm có những loại khác nhau, thông thường nếu cần thay đổi loại của sản phẩm, người sử dụng sẽ sửa sản phẩm đó và thay đổi loại. Nếu trong trường hợp cần thay đổi nhiều sản phẩm người sử dụng sẽ phải mất nhiều thao tác, nhiều thời gian để thực hiện. Vậy làm sao để có thể thay đổi đồng loạt loại cho những sản phẩm được  chọn, bài viết dưới đây sẽ hướng dẫn các bạn làm việc đó.

Xem những Video hay dành cho thiếu nhi - Nghe trên Youtube



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





B1: Download CSDL Northwind

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

USE [Northwind]
GO

CREATE PROCEDURE [dbo].[Pro_Products_List]
      @Keyword nvarchar(250),
      @SupplierID int,
      @CategoryID int
AS

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

set @strSQL= 'SELECT  Products.ProductID, Products.ProductName, Products.SupplierID, Suppliers.CompanyName, Products.CategoryID,
                      Categories.CategoryName, Products.QuantityPerUnit, Products.UnitPrice, Products.UnitsInStock,
                                Products.UnitsOnOrder, Products.ReorderLevel, Products.Discontinued
                    FROM    Products INNER JOIN
                      Suppliers ON Products.SupplierID = Suppliers.SupplierID INNER JOIN
                      Categories ON Products.CategoryID = Categories.CategoryID'

set @strWhere =' Where 1=1 '

if @Keyword<>''
      set @strWhere= @strWhere  +' And (ProductName like N''%' +@Keyword+'%'')'

if @SupplierID <>-1
    set  @strWhere= @strWhere + ' and (Products.SupplierID='+ convert(nvarchar,@SupplierID) + ')'

if @CategoryID <>-1
    set  @strWhere= @strWhere + ' and (Products.CategoryID='+ convert(nvarchar,@CategoryID) + ')'

set @strOrder =' Order by Products.ProductName'

set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql @strSQL
Go
create PROCEDURE [dbo].[Pro_Products_UpdateByCategory]
      @ProductID int,
      @CategoryID int
AS

UPDATE Products SET
      CategoryID = @CategoryID
WHERE
      ProductID = @ProductID
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

- B3: 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 UpdateDatabaseOnCheckboxChangeGridview

    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 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 Object
            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
                Return cmd.ExecuteScalar
            Catch ex As Exception
                Return Nothing
            End Try
        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

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

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

B6: Tạo thư mục UserControls

B7: Tạo file Popup_ChangeCategory.ascx trong thư mục vừa tạo, mở file Popup_ChangeCategory.ascx dưới dạng HTML và  nhập mã HTML

<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="Popup_ChangeCategory.ascx.vb" Inherits="UpdateMultipleValuesfromCheckBoxtoDatabase.UserControls.Popup_ChangeCategory" %>
<%@ Register TagPrefix="cc1" Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" %>

<asp:Panel ID="pnlpopup" runat="server" style="display:none">
    <asp:UpdatePanel ID="updatePanelPopup" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Button id="cmdShowPopup" runat="server" style="display:none" />
            <cc1:ModalPopupExtender ID="ModalPopupExtender_Popup" runat="server" TargetControlID="cmdShowPopup" X="720" Y="220"
                PopupControlID="pnlpopup" CancelControlID="cmdCancel" BackgroundCssClass="ModalPopupBG" Drag="True" />
                <div class="modal" style="width:400px;">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" id="cmdClose" runat="server" causesvalidation="false" class="close" data-dismiss="modal" aria-hidden="true">x</button>
                                <h4 class="modal-title">
                                    <asp:label id="lblHeader" runat="server" Text="Change Category"></asp:label>
                                </h4>
                              </div>
                              <div class="modal-body">
                                   <table width="100%" cellpadding="2" cellspacing="3">
                                       <tr>
                                            <td>
                                                <asp:label id="plCategory" runat="server" CssClass="label" Text="Category"></asp:label>
                                                <asp:Label ID="lblListItem" runat="server" Visible="false"></asp:Label>
                                            </td>
                                            <td>
                                                <asp:DropDownList ID="ddlCategory" CssClass="form-control" runat="server" Width="300px"></asp:DropDownList>
                                            </td>
                                       </tr>
                                   </table>
                              </div>
                              <div class="modal-footer">
                                   <div class="btn-group">
                                        <asp:LinkButton id="cmdUpdate" runat="server" CssClass="btn btn-small" Causesvalidation="true">
                                            <i class="icon-update"></i>&nbsp;&nbsp;<asp:label id="lblUpdate" runat="server" Text="Update"></asp:label>
                                        </asp:LinkButton>
                                        <asp:LinkButton id="cmdCancel" runat="server" CssClass="btn btn-small" Causesvalidation="false">
                                            <i class="icon-close"></i>&nbsp;&nbsp;<asp:label id="lblClose" runat="server" Text="Close"></asp:label>
                                        </asp:LinkButton>
                                   </div>
                              </div>
                        </div>
                    </div>
                </div>
        </ContentTemplate>
    </asp:UpdatePanel>   
</asp:Panel>   


B8: Viết Code cho file Popup_ChangeCategory.ascx

Namespace UpdateMultipleValuesfromCheckBoxtoDatabase.UserControls
    Partial Class Popup_ChangeCategory
        Inherits System.Web.UI.UserControl

#Region "Event Click"

        Public Delegate Sub MyEventHandler(ByVal sender As Object, ByVal e As MyEventArgs)
        Public Event OnSelectedRow As MyEventHandler

#End Region

#Region "Private Methods"

        Private Sub UpdateRecord(ByVal CategoryID As Integer)
            Dim objSQL As New SqlDataProvider

            If lblListItem.Text <> "" Then
                For Each sProduct As String In lblListItem.Text.Split(",")
                    If sProduct <> "" Then
                        objSQL.RunSQL("Pro_Products_UpdateByCategory", New ObjectPara("@ProductID", sProduct), _
                                                    New ObjectPara("@CategoryID", CategoryID))
                    End If
                Next
            End If
        End Sub

#End Region

#Region "Pulbic Methods"

        Public Sub ShowPopup(ByVal ListItem As String)
            LoadComboData()
            lblListItem.Text = ListItem
            updatePanelPopup.Update()
            ModalPopupExtender_Popup.Show()
        End Sub

#End Region

#Region "Data Combo"

        Private Sub LoadDropDownList(ByVal ucControl As DropDownList, ByVal DataValueField As String, ByVal DataTextField As String, ByVal sql As String)
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable(sql)

            ucControl.Items.Clear()

            If Not objBind Is Nothing Then
                With ucControl
                    .DataTextField = DataTextField
                    .DataValueField = DataValueField
                    .DataSource = objBind
                    .DataBind()
                End With
            End If
        End Sub

        Private Sub LoadComboData()
            Dim sSQL As String = "Select CategoryID,CategoryName From Categories"
            LoadDropDownList(ddlCategory, "CategoryID", "CategoryName", sSQL)
        End Sub

#End Region

#Region "Event Handles"

        Private Sub cmdUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click
            Dim MyArgs As New MyEventArgs()
            Dim CategoryID As Integer = -1

            If ddlCategory.SelectedValue <> -1 Then
                CategoryID = ddlCategory.SelectedValue
                UpdateRecord(CategoryID)
                MyArgs.Id = CategoryID
                RaiseEvent OnSelectedRow(Me, MyArgs)
                ModalPopupExtender_Popup.Hide()
            End If
        End Sub

        Private Sub cmdNo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdCancel.Click
            ModalPopupExtender_Popup.Hide()
        End Sub

        Private Sub cmdClose_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdClose.ServerClick
            ModalPopupExtender_Popup.Hide()
        End Sub

#End Region

    End Class

End Namespace

B9: Mở file Default.aspxdưới dạng HTML và  nhập mã HTML

<%@ Page Title="Update Multiple Values from CheckBox to Database in Asp.net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" EnableEventValidation= "false" CodeBehind="Default.aspx.vb" Inherits="UpdateMultipleValuesfromCheckBoxtoDatabase._Default" %>
<%@ Register TagPrefix="ModalPopup" TagName="ChangeCategory" Src="~/UserControls/Popup_ChangeCategory.ascx"%>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <h3>
        Update Multiple Values from CheckBox to Database in Asp.net
    </h3>
    <ModalPopup:ChangeCategory ID="ucChangeCategory" runat="server" />
    <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="2" cellspacing="3" width="100%">
                <tr>
                    <td>
                        <asp:LinkButton id="cmdChange" runat="server" CssClass="btn btn-small" CausesValidation="false" Text="Change Category">
                           
                        </asp:LinkButton>
                    </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" Text="No Data"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:GridView ID="grvObject" runat="server" AllowPaging="true" PageSize="12"
                            CssClass="GridStyle" BorderColor="#cbcbcb" BorderStyle="solid"
                            BorderWidth="1" AutoGenerateColumns="false" DataKeyNames="ProductID" width="100%">
                            <AlternatingRowStyle CssClass="GridStyle_AltRowStyle" />
                            <HeaderStyle CssClass="GridStyle_HeaderStyle" />
                            <RowStyle CssClass="GridStyle_RowStyle" />
                            <pagerstyle cssclass="GridStyle_pagination" />
                            <Columns>
                                <asp:TemplateField>
                                    <ItemStyle HorizontalAlign="Center" width="1%" />
                                    <HeaderTemplate>
                                        <asp:CheckBox ID="chkAll" runat="server" />
                                    </HeaderTemplate>
                                    <ItemTemplate>
                                        <asp:CheckBox ID="chkSelect" runat="server" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText = "Number">
                                    <ItemStyle HorizontalAlign="Center" Width="2%"></ItemStyle>
                                    <ItemTemplate>
                                        <asp:Label ID="lblRowNumber" Text='<%# Container.DataItemIndex + 1 %>' runat="server" />
                                        <asp:Label ID="lblProductID" Text='<%# Eval("ProductID") %>' Visible="false" runat="server"></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:BoundField ItemStyle-Width="15%" DataField="ProductName" HeaderText="ProductName" />
                                <asp:BoundField ItemStyle-Width="15%" DataField="CompanyName" HeaderText="CompanyName" />
                                <asp:BoundField ItemStyle-Width="8%" DataField="CategoryName" HeaderText="CategoryName" />
                                <asp:BoundField ItemStyle-Width="10%" DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" />
                                <asp:BoundField ItemStyle-Width="5%" DataField="UnitPrice" ItemStyle-HorizontalAlign="Right" HeaderText="UnitPrice" />
                            </Columns>                              
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

B10: Viết Code cho file Default.aspx

'Visit http://thuthuatlaptrinh.blogspot.com for more ASP.NET Tutorials

Namespace UpdateMultipleValuesfromCheckBoxtoDatabase

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Bind Data"

        Private Sub BindProduct()
            Dim objBind As New DataTable
            objBind = BindData()

            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
                End If
            End If
            updatePanel.Update()
        End Sub

        Private Function BindData() As DataTable
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable("Pro_Products_List", New ObjectPara("@Keyword", txtSearch.Text.Trim), _
                                                                          New ObjectPara("@SupplierID", -1), _
                                                                          New ObjectPara("@CategoryID", -1))
            Return objBind
        End Function

#End Region

#Region "GridView Methods"

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

#End Region

#Region "Popup"

        Private Sub MySel_OnSelectedRow(ByVal sender As Object, ByVal e As UpdateMultipleValuesfromCheckBoxtoDatabase.MyEventArgs)
            Dim ItemName As String = ""
            With e
                If e.Id <> "" Then
                    BindProduct()
                End If
            End With
        End Sub

#End Region

#Region "Event Handles"

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try
                AddHandler CType(ucChangeCategory, UserControls.Popup_ChangeCategory).OnSelectedRow, AddressOf MySel_OnSelectedRow
                If Page.IsPostBack = False Then
                    'Default Submit Button
                    Page.Form.DefaultButton = cmdQuickSearch.UniqueID
                    BindProduct()
                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
            BindProduct()
        End Sub

        Private Sub cmdChange_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdChange.Click
            Dim intCount As Integer = grvObject.Rows.Count
            Dim chkSelect As CheckBox
            Dim lblLabel As Label
            Dim i As Integer
            Dim ListProduct As String = ""

            For i = 0 To intCount - 1
                chkSelect = CType(grvObject.Rows(i).FindControl("chkSelect"), CheckBox)
                lblLabel = CType(grvObject.Rows(i).FindControl("lblProductID"), Label)
                If Not chkSelect Is Nothing And Not lblLabel Is Nothing Then
                    Dim ProductID As String = ""
                    If Not lblLabel Is Nothing Then
                        ProductID = lblLabel.Text
                    End If
                    If ProductID <> -1 AndAlso chkSelect.Checked Then
                        ListProduct &= ProductID & ","
                    End If
                End If
            Next

            If ListProduct.Length > 1 Then
                If ListProduct.EndsWith(",") Then ListProduct = ListProduct.Remove(ListProduct.Length - 1, 1)
            End If

            If ListProduct <> "" Then
                With CType(ucChangeCategory, UserControls.Popup_ChangeCategory)
                    .ShowPopup(ListProduct)
                End With
            End If
        End Sub

#End Region

    End Class

End Namespace

Bây giờ chạy Project, tích chọn các giá  trị cần thay đổi loại -> Kích nút Change Category -> Hộp thoại xuất hiện -> Lựa chọn loại cần thay đổi -> Kích nút Update. Toàn bộ các sản phẩm được chọn sẽ được thay đổi loại đã được chọn.

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:

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 " Cập nhật đồng loạt nhiều giá trị vào Database trên Gridview "

  • 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