News Ticker

Menu

Hiển thị icon theo loại tài liệu trong Gridview

(Showing icon in gridview according to type of document) –  Khi hiển thị danh sách tài liệu trên Gridview, nếu chỉ để tên tài liệu người sử dụng rất khó biết được loại file của từng tài liệu. Nếu bổ xung thêm cột Icon thể hiện từng loại file vừa giúp Gridview chuyên nghiệp hơn lại giúp người sử dụng dễ dàng hơn trong việc sử dụng và download khi cần thiết. Bài viết dưới đây sẽ hướng dẫn các bạn cách hiển thị Icon theo từng loại tài liệu và mỗi khi kích vào tên tài liệu, cửa sổ Popup xuất hiện cho phép người dùng Download file.

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: Tạo CSDL Demo_Documents trong SQL Server

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

STTTên trườngKiểu trườngGhi chú
1DocumentIDIntTrường tự tăng
2DocumentNamenvarchar(250)
3FileNamenvarchar(250)
4FileSizenvarchar(50)
5Descriptionnvarchar(250)
6CreatedDatedatetime
7ModifiedDatedatetime

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

B4: Tạo stored procedure trong SQL Server

USE [Demo_Documents]
GO

CREATE PROCEDURE [dbo].[Pro_Documents_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 Documents'
set @strWhere =' Where 1=1 '

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

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

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

CREATE PROCEDURE [dbo].[Pro_Documents_Get]
      @DocumentID int
AS

SELECT * FROM Documents
WHERE
      DocumentID = @DocumentID

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 ShowingIconGridviewAccordingtoTypeofDocument

    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 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: Mở file Default.aspxdưới dạng HTML và  nhập mã HTML

<%@ Page Title="Showing Icon in Gridview according to type of Document" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" EnableEventValidation= "false" CodeBehind="Default.aspx.vb" Inherits="ShowingIconGridviewAccordingtoTypeofDocument._Default" %>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <h3>
        Showing Icon in Gridview according to type of Document
    </h3>
    <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" 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="DocumentID" width="100%">
                            <AlternatingRowStyle CssClass="GridStyle_AltRowStyle" />
                            <HeaderStyle CssClass="GridStyle_HeaderStyle" />
                            <RowStyle CssClass="GridStyle_RowStyle" />
                            <pagerstyle cssclass="GridStyle_pagination" />
                            <Columns>
                                <asp:TemplateField HeaderText = "Number">
                                    <ItemStyle HorizontalAlign="Center" Width="2%"></ItemStyle>
                                    <ItemTemplate>
                                        <asp:Label ID="lblRowNumber" Text='<%# Container.DataItemIndex + 1 %>' runat="server" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField>
                                    <ItemStyle HorizontalAlign="Center" width="1%" />   
                                    <ItemTemplate>
                                         <asp:Image ID="imgIcon" runat="server" />
                                    </ItemTemplate>                          
                                </asp:TemplateField> 
                   
                                <asp:TemplateField HeaderText="DocumentName">
                                    <ItemStyle width="20%" />   
                                    <ItemTemplate>
                                        <asp:LinkButton id="cmdDownload" runat="server" CommandName="Download" CommandArgument='<%# Eval("DocumentID") %>'  CssClass="Title" text='<%# Eval("DocumentName") %>'></asp:LinkButton>
                                    </ItemTemplate>                          
                                </asp:TemplateField>
                                <asp:BoundField ItemStyle-Width="15%" DataField="FileName" HeaderText="FileName" />
                                <asp:BoundField ItemStyle-Width="8%" DataField="FileSize" HeaderText="FileSize" />
                                <asp:BoundField ItemStyle-Width="12%" DataField="CreatedDate" HeaderText="CreatedDate" />        
                            </Columns>                              
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

B7: Viết Code cho file Default.aspx

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

Namespace ShowingIconGridviewAccordingtoTypeofDocument

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Private Methods"

        Private strExtension As String = ""
        Private filePath As String = ""

#End Region

#Region "Private Methods"

        Private Function FormatIconURL(ByVal FileExtension As String) As String
            Dim strImage As String = ""
            strImage = IIf(HttpContext.Current.Request.ApplicationPath = "/", HttpContext.Current.Request.ApplicationPath, HttpContext.Current.Request.ApplicationPath & "/") & "Images/icons/" & FileExtension & ".gif"
            If Not File.Exists(HttpContext.Current.Server.MapPath(strImage)) Then
                strImage = IIf(HttpContext.Current.Request.ApplicationPath = "/", HttpContext.Current.Request.ApplicationPath, HttpContext.Current.Request.ApplicationPath & "/") & "Images/icons/" & FileExtension & ".png"
                If Not File.Exists(HttpContext.Current.Server.MapPath(strImage)) Then
                    strImage = IIf(HttpContext.Current.Request.ApplicationPath = "/", HttpContext.Current.Request.ApplicationPath, HttpContext.Current.Request.ApplicationPath & "/") & "Images/icons/" & FileExtension & ".jpg"
                    If Not File.Exists(HttpContext.Current.Server.MapPath(strImage)) Then
                        strImage = IIf(HttpContext.Current.Request.ApplicationPath = "/", HttpContext.Current.Request.ApplicationPath, HttpContext.Current.Request.ApplicationPath & "/") & "/Images/icons/unknown.gif"
                    End If
                End If
            End If
            Return strImage
        End Function

        Private Function GetFileName(ByVal ItemID As Integer) As String
            Dim objSQL As New SqlDataProvider
            Dim FileName As String = ""
            Dim objInfo As DataRow = objSQL.GetRow("Pro_Documents_Get", New ObjectPara("@DocumentID", ItemID))
            If Not objInfo Is Nothing Then
                If Not IsDBNull(objInfo("FileName")) Then
                    FileName = objInfo("FileName")
                End If
            End If
            Return FileName
        End Function

        Private Sub DownloadFile(ByVal filepath As String)
            If filepath <> "" Then
                Dim file As New System.IO.FileInfo(filepath)

                If file.Exists Then
                    Response.Clear()
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name)
                    Response.AddHeader("Content-Length", file.Length.ToString())
                    Response.ContentType = "application/octet-stream"
                    Response.WriteFile(file.FullName)
                    Response.End()
                Else
                    Response.Write("This file does not exist.")
                End If
            Else
                Response.Write("Please provide a file to download.")
            End If
        End Sub

#End Region

#Region "Bind Data"

        Private Sub BindDocument()
            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 Function BindData() As DataTable
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable("Pro_Documents_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 Sub grvObject_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grvObject.RowCommand
            Dim ItemID As Integer = Integer.Parse(e.CommandArgument)
            Dim FileName As String = ""
            Select Case e.CommandName.ToLower
                Case "download"
                    FileName = GetFileName(ItemID)
                    filePath = MapPath("~/Documents/") & FileName
                    If File.Exists(filePath) Then
                        DownloadFile(filePath)
                    End If
            End Select
        End Sub

        Private Sub grvObject_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles grvObject.RowDataBound
            If e.Row.RowType = DataControlRowType.DataRow Then
                Dim FileName As String = DataBinder.Eval(e.Row.DataItem, "FileName")

                Dim imgIcon As Image = CType(e.Row.FindControl("imgIcon"), Image)
                If FileName <> "" Then
                    strExtension = Replace(Path.GetExtension(FileName), ".", "")
                End If

                If Not imgIcon Is Nothing Then
                    imgIcon.ImageUrl = FormatIconURL(strExtension)
                    imgIcon.ImageAlign = ImageAlign.Middle
                End If

                Dim cmdDownload As LinkButton = CType(e.Row.FindControl("cmdDownload"), LinkButton)
                If cmdDownload IsNot Nothing Then
                    cmdDownload.ToolTip = "Click to Download"
                    ScriptManager.GetCurrent(Page).RegisterPostBackControl(cmdDownload)
                End If
            End If
        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
            BindDocument()
        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
                    BindDocument()
                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
            BindDocument()
        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 " Hiển thị icon theo loại tài liệu trong 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