(Export các cột được chọn ra Excel trong Asp.net) –  Khi thực hiện công việc Export danh sách dữ liệu ra Excel, tùy vào từng thời điểm và mục đích công việc mà danh sách cột dữ liệu sẽ khác nhau. Nếu như phần mềm không hỗ trợ việc lựa chọn trường dữ liệu để Export người sử dụng sẽ phải Export và xóa đi những trường không cần đến. Vậy có cách nào để cho phép người sử dụng có thể dễ dàng chọn hoặc bỏ chọn trường dữ liệu khi Export sang Excel? Bài viết dưới đây sẽ hướng dẫn các bạn làm điều đó, chương trình sẽ tự động lấy toàn bộ các trường dữ liệu có trong 1 bảng dữ liệu, từ đó người dùng có thể chọn hoặc bỏ chọn những trường không cần thiết để Export ra file Excel.

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 SQL Customers

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

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

USE [Customers]
GO

CREATE PROCEDURE [dbo].[Pro_Accounts_Get]
      @AccountID int
AS

SELECT * FROM Accounts
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

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 ExportSelectedColumnsToExcel

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

        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

    Public Class MyEventArgs
        Inherits EventArgs

        Private Name As String
        Private MyId As String

        Public PropertySelectedName() As String
            Get
                Return Name
            End Get
            Set(ByVal value As String)
                Name = value
            End Set
        End Property

        Public Property Id() As String
            Get
                Return MyId
            End Get
            Set(ByVal value As String)
                MyId = 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ỉ: http://ajaxcontroltoolkit.codeplex.com/downloads/get/116534

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, Copy ảnh lần lượt vào các thư mục Images

+ delete.gif, icon_search.gif vào thư mục Images
+ no.png, yes.png, sprite.png, lt.gif,  icon_excel.png vào thư mục  Styles\Images


B9: Tạo thư mục UserControls, thêm file Popup_SelectedColumns.ascx và nhập mã HTML

<%@ ControlLanguage="vb"AutoEventWireup="false"CodeBehind="Popup_SelectedColumns.ascx.vb"Inherits="ExportSelectedColumnsToExcel.UserControls.Popup_SelectedColumns"%>
<%@ RegisterTagPrefix="cc1"Assembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"%>

<script language="javascript" type="text/javascript">
    function CheckBoxListSelect(cbControl, state) {
        var chkBoxList = document.getElementById(cbControl);
        var chkBoxCount = chkBoxList.getElementsByTagName("input");
        for (var i = 0; i < chkBoxCount.length; i++) {
            chkBoxCount[i].checked = state;
        }
        return false;
    }
</script>

<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="750"Y="150"
                PopupControlID="pnlpopup"CancelControlID="cmdCancel"BackgroundCssClass="ModalPopupBG"Drag="True"/>
                <divclass="modal"style="width:450px;">
                    <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="Export only selected columns to Excel"></asp:label>
                                </h4>
                              </div>
                              <div class="modal-body">
                                   <table width="100%"cellpadding="0"cellspacing="0">
                                       <tr>
                                            <td style="padding-left:10px;padding-bottom:5px;">
                                                 <a id="A1" href="#" onclick="javascript: CheckBoxListSelect ('<%= chkExport.ClientID %>',true)">
                                                       <asp:label id="plCheckAll"runat="server"CssClass="NormalBold"text="CheckAll"></asp:label>
                                                  </a>|
                                                  <a id="A2" href="#" onclick="javascript: CheckBoxListSelect ('<%= chkExport.ClientID %>',false)">
                                                       <asp:label id="plUnCheckAll" runat="server" CssClass="NormalBold" text="UnCheckAll"></asp:label>
                                                  </a>
                                            </td>
                                       </tr>
                                       <tr>
                                           <td>
                                               <asp:CheckBoxList ID="chkExport"CellPadding="5"CellSpacing="10"RepeatColumns="2"runat="server">
                                               </asp:CheckBoxList>
                                           </td>
                                       </tr>
                                   </table>
                              </div>
                              <div class="modal-footer">
                                   <div class="btn-group">
                                        <asp:LinkButton id="cmdOK" runat="server"CssClass="btn btn-small" CausesValidation="false">
                                            <i class="icon-exportexcel"></i>&nbsp;&nbsp;<asp:label id="lblExport" runat="server" Text="Export"></asp:label>
                                        </asp:LinkButton>&nbsp;
                                         <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>
        <Triggers>
            <asp:PostBackTrigger ControlID="cmdOK"/>
        </Triggers>
    </asp:UpdatePanel>   
</asp:Panel>    

B10: Tạo thư mục UserControls, thêm file Popup_SelectedColumns.ascx và nhập mã HTML

Imports iTextSharp.text.html
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf

Namespace ExportSelectedColumnsToExcel.UserControls
    Partial Class Popup_SelectedColumns
        Inherits System.Web.UI.UserControl

#Region "Private Members"

        Private _ItemID As Integer
        Private _ItemName As String

#End Region

#Region "Event Click"

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

#End Region

#Region "Private Methods"

        Private Function GetColumnNames(ByVal TableName As StringAs IEnumerable(Of String)
            Dim ColumnNames = New List(Of String)()
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable("Select COLUMN_NAME, DATA_TYPE FROM information_schema.columns where TABLE_NAME ='" & TableName & "'")

            If Not objBind Is Nothing Then
                For Each row As DataRow In objBind.Rows
                    ColumnNames.Add(row.Field(Of String)("COLUMN_NAME"))
                Next
            End If
            Return ColumnNames
        End Function

#End Region

#Region "GetColumnNames"

        Private Sub BindColumn()
            Dim TableName As String = "Accounts"
            Dim ColumnNames = GetColumnNames(TableName)
            Dim i As Integer = 0
            chkExport.Items.Clear()
            For Each columnName As String In ColumnNames
                chkExport.Items.Add(New System.Web.UI.WebControls.ListItem(columnName, columnName))
                chkExport.Items(i).Selected = True
                i = i + 1
            Next
        End Sub

#End Region

#Region "Pulbic Methods"

        Public Sub ShowPopup(ByVal ItemID As Integer)
            BindColumn()
            updatePanelPopup.Update()
            ModalPopupExtender_Popup.Show()
        End Sub

        Public Sub HidePopup()
            ModalPopupExtender_Popup.Hide()
        End Sub

#End Region

#Region "Properties"

        Public Property ItemID() As Integer
            Get
                Return _ItemID
            End Get
            Set(ByVal Value As Integer)
                _ItemID = Value
            End Set
        End Property

        Public Property ItemName() As String
            Get
                Return _ItemName
            End Get
            Set(ByVal Value As String)
                _ItemName = Value
            End Set
        End Property

#End Region

#Region "Event Handles"

        Private Sub cmdOK_Click(ByVal sender As ObjectByVal e As System.EventArgsHandles cmdOK.Click
            Dim MyArgs As New MyEventArgs()
            Dim sListExport As String = ""
            Dim i As Integer = 0
            Dim iCount As Integer = 0

            For i = 0 To chkExport.Items.Count - 1
                If chkExport.Items(i).Selected Then
                    sListExport &= chkExport.Items(i).Value & ","
                    iCount = iCount + 1
                End If
            Next

            If sListExport.Length > 0 And sListExport.EndsWith(","Then
                sListExport = sListExport.Remove(sListExport.Length - 1, 1)
            End If

            ModalPopupExtender_Popup.Hide()

            MyArgs.Id = sListExport
            MyArgs.SelectedName = iCount
            RaiseEvent OnSelectedRow(Me, MyArgs)
        End Sub

        Private Sub cmdCancel_Click(ByVal sender As ObjectByVal e As System.EventArgsHandles cmdCancel.Click
            ModalPopupExtender_Popup.Hide()
        End Sub

        Private Sub cmdClose_ServerClick(ByVal sender As ObjectByVal e As System.EventArgsHandles cmdClose.ServerClick
            ModalPopupExtender_Popup.Hide()
        End Sub

#End Region

    End Class

End Namespace


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

<%@ PageTitle="Export Selected Columns to Excel in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="ExportSelectedColumnsToExcel._Default" %>
<%@ RegisterTagPrefix="ModalPopup"TagName="Delete"Src="~/UserControls/Popup_ConfirmDelete.ascx"%>
<%@ RegisterTagPrefix="ModalPopup"TagName="Export"Src="~/UserControls/Popup_SelectedColumns.ascx"%>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1"runat="server">
    </asp:ScriptManager>
    <h1>
        Export Selected Columns to Excel in ASP.Net
    </h1>
    <br />
    <ModalPopup:Export ID="ucSelectedColumns"runat="server"/>
    <ModalPopup:Delete ID="ucDeleteItem"runat="server"/>
    <asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="2"cellspacing="3"width="100%">
                <tr>
                    <td>
                        <asp:LinkButton id="cmdExport" runat="server" CssClass="btn btn-small" Causesvalidation="false">
                            <i class="icon-exportexcel"></i>&nbsp;&nbsp;<asp:label id="lblExport" runat="server" Text="ExportToExcel"></asp:label>
                        </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="8"
                            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"/>
                            <pagerstyle cssclass="GridStyle_pagination" />
                            <Columns>
                                <asp:BoundField ItemStyle-Width="10%"DataField="AccountCode"HeaderText="AccountCode"/>
                                <asp:BoundField ItemStyle-Width="15%"DataField="AccName"HeaderText="AccountName"/>
                                <asp:BoundField ItemStyle-Width="10%"DataField="AccPhone"HeaderText="Phone"/>
                                <asp:BoundField ItemStyle-Width="10%"DataField="AccFAX"HeaderText="FAX"/>
                                <asp:BoundField ItemStyle-Width="15%"DataField="AccEmail"HeaderText="Email"/>       
                                      <asp:TemplateField HeaderText="Function">
                                          <ItemStyle HorizontalAlign="Center" width="5%" /> 
                                             <ItemTemplate>
                                        <asp:ImageButton ID="cmdDelete"CommandName="Delete"CommandArgument='<%# Eval("AccountID")%>' runat="server"ImageUrl="~/images/delete.gif"CausesValidation="False"></asp:ImageButton>
                                             </ItemTemplate>
                                      </asp:TemplateField>                                
                            </Columns>                                                  
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
        <Triggers>
            <asp:PostBackTrigger ControlID="cmdExport"/>
        </Triggers>
    </asp:UpdatePanel>
</asp:Content>

B12: Viết Code cho file Default.aspx

Namespace ExportSelectedColumnsToExcel

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Export Excel"

        Private FunctionInserHeaderInExcel() As String
            Dim sExportToExcel AsString = ""

            sExportToExcel &= "<table border='0' cellpadding='0' cellspacing='0' width='99%' align='center'>"& vbCrLf
            sExportToExcel &= "<tr>"& vbCrLf
            sExportToExcel &= "<td colspan='3' style='font-size:14pt;'><b>THỦ THUẬT LẬP TRÌNH</b></td>"& vbCrLf
            sExportToExcel &= "</tr>"& vbCrLf
            sExportToExcel &= "<tr>"& vbCrLf
            sExportToExcel &= "<td colspan='3'><b>Website:</b> http://thuthuatlaptrinh.blogspot.com</td>" & vbCrLf
            sExportToExcel &= "</tr>"& vbCrLf
            sExportToExcel &= "<tr>"& vbCrLf
            sExportToExcel &= "<td colspan='3'><b>Email:</b> kenhphanmemviet@gmail.com</td>" & vbCrLf
            sExportToExcel &= "</tr>"& vbCrLf
            sExportToExcel &= "</table>"& vbCrLf
            Return sExportToExcel
        End Function

        Private SubMySelExport_OnSelectedRow(ByVal sender As Object, ByVal e AsExportSelectedColumnsToExcel.MyEventArgs)
            Dim sExportList As String = ""
            Dim iCount As Integer = 0
            With e
                If e.Id <> "" Then
                    sExportList = e.Id
                    iCount = e.SelectedName
                    If sExportList <> "" Then
                        ExportToExcel("List-Account.xls", sExportList, iCount)
                    End If
                End If
            End With
        End Sub

        Private FunctionExportAccountToExcel(ByVal objBind As DataTable, ByVal FileName As String, ByValExportList As String, ByVal iCount AsInteger) As String
            Dim sExportToExcel AsString = ""
            Dim dColumn As DataColumn

            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then

                    sExportToExcel &= InserHeaderInExcel()

                    sExportToExcel &= "<table border='0' cellpadding='0' cellspacing='0' width='99%' align='center'>"& vbCrLf
                    sExportToExcel &= "<tr>"& vbCrLf
                    sExportToExcel &= "<td colspan="& iCount & ">&nbsp;</td>"& vbCrLf
                    sExportToExcel &= "</tr>"& vbCrLf
                    sExportToExcel &= "<tr>"& vbCrLf
                    sExportToExcel &= "<td align='center' colspan=" & iCount & " style='font-size:12pt;'><b>LIST ACCOUNT</b></td>" & vbCrLf
                    sExportToExcel &= "</tr>"& vbCrLf

                    sExportToExcel &= "<tr>"& vbCrLf
                    sExportToExcel &= "<td colspan=" & iCount & ">&nbsp;</td>"& vbCrLf
                    sExportToExcel &= "</tr>"& vbCrLf
                    sExportToExcel &= "</table>"& vbCrLf

                    sExportToExcel &= "<table border='1' cellpadding='0' cellspacing='0' width='99%' align='center'>"& vbCrLf
                    'Header
                    sExportToExcel &= "<tr>" & vbCrLf
                    For EachsValue As StringIn ExportList.Split(",")
                        sExportToExcel &= "<td align='center'><b>"& sValue & "</b></td>"& vbCrLf
                    Next
                    sExportToExcel &= "</tr>"& vbCrLf

                    For Eachrow As DataRowIn objBind.Rows
                        sExportToExcel &= "<tr>" & vbCrLf
                        For Each sValue As String In ExportList.Split(",")
                            For Each dColumn In objBind.Columns
                                If sValue = dColumn.ColumnName Then
                                    If NotIsDBNull(row(sValue)) Then
                                        sExportToExcel &= "<td>"& row(sValue).ToString & "</td>"& vbCrLf
                                    Else
                                        sExportToExcel &= "<td></td>"& vbCrLf
                                    End If
                                End If
                            Next
                        Next
                        sExportToExcel &= "</tr>" & vbCrLf
                    Next
                    sExportToExcel &= "</table>"& vbCrLf
                End If
            End If
            ReturnsExportToExcel
        End Function

        Private SubExportToExcel(ByVal FileName As String, ByVal ExportList As String, ByVal iCount As Integer)
            Dim objBind As New DataTable

            Dim sb As New System.Text.StringBuilder
            DimsExportToExcel As String= ""
            Dim style As String = "<style>.text{mso-number-format:\@;}</style>"

            objBind = BindData()

            If objBind.Rows.Count > 0 Then
                sExportToExcel = ExportAccountToExcel(objBind, FileName, ExportList, iCount)

                sb.Append(sExportToExcel)
                lblExport.Text = sb.ToString()
                sb.Remove(0, sb.Length)

                Response.Clear()
                Response.Charset = ""
                Response.ContentEncoding = System.Text.Encoding.UTF8
                Response.Cache.SetCacheability(HttpCacheability.NoCache)
                Response.ContentType = "application/ms-excel.xls"
                Response.AddHeader("content-disposition", "attachment;filename=" & FileName & ".xls")
                Response.ContentEncoding = Encoding.Unicode
                Response.BinaryWrite(Encoding.Unicode.GetPreamble())

                Dim sw AsNew System.IO.StringWriter
                Dim htw As New HtmlTextWriter(sw)

                lblExport.RenderControl(htw)
                Response.Output.Write(style & sw.ToString().Replace("td", "td class='text'"))
                Response.Flush()
                Response.End()
            End If
        End Sub

#End Region

#Region "Bind Data"

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

        Private FunctionBindData() As DataTable
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable("Pro_Accounts_List", New ObjectPara("@Keyword", txtSearch.Text.Trim), _
                                                                          New ObjectPara("@SortField", "CreatedDate"), _
                                                                          New ObjectPara("@SortType", "DESC"))
            Return objBind
        End Function

#End Region

#Region "GridView Methods"

        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)
            Dim ItemName As String = ""
            If ItemID <> -1 Then
                With CType(ucDeleteItem, ExportSelectedColumnsToExcel.UserControls.Popup_ConfirmDelete)
                    .ItemID = ItemID
                    .ShowPopup(ItemID, "")
                End With
            End If
        End Sub

        Private SubgrvObject_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) HandlesgrvObject.RowDataBound
            If (e.Row.RowType = DataControlRowType.DataRow) Then
                'Delete
                Dim cmdDelete AsImageButton = DirectCast(e.Row.FindControl("cmdDelete"), ImageButton)
                If NotcmdDelete Is NothingThen
                    cmdDelete.ToolTip = "Delete Account"
                End If
            End If
        End Sub

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

#End Region

#Region "Popup"

        Private SubMySelDelete_OnSelectedRow(ByVal sender As Object, ByVal e AsExportSelectedColumnsToExcel.MyEventArgs)
            Dim ItemName As String = ""
            With e
                If e.Id <> "" Then
                    BindAccount()
                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(ucDeleteItem, ExportSelectedColumnsToExcel.UserControls.Popup_ConfirmDelete).OnSelectedRow, AddressOf MySelDelete_OnSelectedRow
                AddHandler CType(ucSelectedColumns, ExportSelectedColumnsToExcel.UserControls.Popup_SelectedColumns).OnSelectedRow, AddressOf MySelExport_OnSelectedRow

                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

        Private SubcmdExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdExport.Click
            With CType(ucSelectedColumns, ExportSelectedColumnsToExcel.UserControls.Popup_SelectedColumns)
                .ShowPopup(-1)
            End With
        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