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

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: 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 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 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 Object
            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
                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 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

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

<%@ ControlLanguage="vb"AutoEventWireup="false"CodeBehind="Popup_ChangeCategory.ascx.vb"Inherits="UpdateMultipleValuesfromCheckBoxtoDatabase.UserControls.Popup_ChangeCategory"%>
<%@ RegisterTagPrefix="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:ModalPopupExtenderID="ModalPopupExtender_Popup"runat="server"TargetControlID="cmdShowPopup"X="720"Y="220"
                PopupControlID="pnlpopup"CancelControlID="cmdCancel"BackgroundCssClass="ModalPopupBG"Drag="True"/>
                <divclass="modal"style="width:400px;">
                    <divclass="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

NamespaceUpdateMultipleValuesfromCheckBoxtoDatabase.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 EventOnSelectedRow As MyEventHandler

#End Region

#Region "Private Methods"

        Private SubUpdateRecord(ByVal CategoryID As Integer)
            Dim objSQL As New SqlDataProvider

            If lblListItem.Text <> ""Then
                For EachsProduct As StringIn 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 SubLoadDropDownList(ByVal ucControl As DropDownList, ByVal DataValueField AsString, ByValDataTextField 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 SubLoadComboData()
            Dim sSQL As String = "Select CategoryID,CategoryName From Categories"
            LoadDropDownList(ddlCategory, "CategoryID", "CategoryName", sSQL)
        End Sub

#End Region

#Region "Event Handles"

        Private SubcmdUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdUpdate.Click
            Dim MyArgs As New MyEventArgs()
            DimCategoryID 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 SubcmdNo_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdCancel.Click
            ModalPopupExtender_Popup.Hide()
        End Sub

        Private SubcmdClose_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdClose.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

<%@ PageTitle="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"%>
<%@ RegisterTagPrefix="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>
                    <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" Text="No Data"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <tdcolspan="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%">
                            <AlternatingRowStyleCssClass="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 SubBindProduct()
            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 FunctionBindData() 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 SubgrvObject_PageIndexChanging(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewPageEventArgs) Handles grvObject.PageIndexChanging
            grvObject.PageIndex = e.NewPageIndex
            BindProduct()
        End Sub

#End Region

#Region "Popup"

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

#End Region

#Region "Event Handles"

        Protected SubPage_Load(ByVal sender AsObject, 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 SubcmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdQuickSearch.Click
            BindProduct()
        End Sub

        Private SubcmdChange_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdChange.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 NotchkSelect Is NothingAnd NotlblLabel Is NothingThen
                    Dim ProductID AsString = ""
                    If NotlblLabel Is NothingThen
                        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(",") ThenListProduct = 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

0 comments Blogger 0 Facebook

Post a Comment

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