Hiển thị danh sách ảnh trên Datalist từ thư mục
(How to display Images in DataList from folder) – Thông thường khi hiển thị ảnh trên Gridview hoặc Datalist, các thông tin như: Tên ảnh, đường dẫn được lưu giữ trong Database, còn file ảnh được lưu giữ dưới thư mục. Bài viết dưới đây sẽ giới thiệu với các bạn cách hiển thị ảnh trên Datalist mà các thông tin ảnh không được lấy trong Database. Các thông tin như tên ảnh, đường dẫn, kích thước hoàn toàn được lấy từ thư mục (Folder) lưu trữ file ảnh.
- B1: Tạo Project trong Microsoft Visual Studio 2010Trong Visual Studio tạo 1 Class có tên: FileSystemItem và nhập đoạn Code phía dưới cho Class này.
C# Code
using System.IO;
public class FileSystemItem
{
public FileSystemItem(FileInfo
file)
{
this.Name = file.Name;
this.FullName = file.FullName;
}
public string Name { get; set; }
public string
FullName { get; set;
}
}
VB.NET Code
Imports System.IO
Public Class FileSystemItem
Public Sub New(ByVal file As FileInfo)
Me.Name = file.Name
Me.FullName = file.FullName
End Sub
Public Property Name As String
Public Property FullName As String
End Class
- B2: Tạo thư mục Images trong Project, Download thư viện ảnh tại đây và Copy vào thư mục vừa tạo
C# Code
<%@ Page
Title="Display
Image In DataList from Folder" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DisplayImageInDataListfromFolder._Default"
%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"
runat="server">
</asp:ScriptManager>
<h3>
Display Images in DataList from folder
</h3>
<style type="text/css">
.frame {
float: left;
width: 160px;
height: 160px;
position: relative;
border: 1px solid #cccccc;
border-radius: 15px;
}
</style>
<asp:UpdatePanel ID="updatePanel"
runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"
cellspacing="3"
width="100%">
<tr>
<td>
<asp:DataList ID="lstEmployees" runat="server" CellPadding="3" CellSpacing="5" Width="100%"
RepeatDirection="Horizontal"
RepeatColumns="5"
OnItemDataBound="lstEmployees_ItemDataBound">
<ItemTemplate>
<table class="frame"
align="left">
<tr>
<td valign="middle"
align="center">
<div id="gallery">
<asp:Image ID="imgEmployee"
runat="server"
Width="100px"></asp:Image>
</div>
</td>
</tr>
<tr>
<td valign="middle"
align="center">
<asp:Label ID="lblName"
Text='<%# Eval("Name") %>' Runat="server" />
</td>
</tr>
</table>
</ItemTemplate>
<ItemStyle VerticalAlign="Top"
/>
</asp:DataList>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>VB.NET Code
<%@ Page
Title="Display
Image In DataList from Folder" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="DisplayImageInDataListfromFolder._Default"
%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"
runat="server">
</asp:ScriptManager>
<h3>
Display Images in DataList from folder
</h3>
<style type="text/css">
.frame {
float: left;
width: 160px;
height: 160px;
position: relative;
border: 1px solid #cccccc;
border-radius: 15px;
}
</style>
<asp:UpdatePanel ID="updatePanel"
runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"
cellspacing="3"
width="100%">
<tr>
<td>
<asp:DataList ID="lstEmployees" runat="server" CellPadding="3" CellSpacing="5" Width="100%" RepeatDirection="Horizontal" RepeatColumns="5">
<ItemTemplate>
<table class="frame"
align="left">
<tr>
<td valign="middle"
align="center">
<div id="gallery">
<asp:Image ID="imgEmployee"
runat="server"
Width="100px"></asp:Image>
</div>
</td>
</tr>
<tr>
<td valign="middle"
align="center">
<asp:Label ID="lblName"
Text='<%# Eval("Name") %>' Runat="server" />
</td>
</tr>
</table>
</ItemTemplate>
<ItemStyle VerticalAlign="Top"
/>
</asp:DataList>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>- B4: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com
for more ASP.NET Tutorials
using System;
using System.Data;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web;
using System.Collections;
using System.Collections.Generic;
namespace DisplayImageInDataListfromFolder
{
public partial class _Default :
System.Web.UI.Page
{
#region "Private Members"
private string
FilePath = "";
#endregion
#region
"Private Methods"
private void
SetFilePath()
{
FilePath = MapPath("~/Images");
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
}
private string
GetFullyQualifiedFolderPath(string folderPath)
{
if (folderPath.StartsWith("~"))
{
return
Server.MapPath(folderPath);
}
else
{
return folderPath;
}
}
#endregion
#region
"Bind Data"
private void
BindData()
{
DirectoryInfo currentDirInfo = new DirectoryInfo(GetFullyQualifiedFolderPath(FilePath));
dynamic folders = currentDirInfo.GetDirectories();
dynamic files = currentDirInfo.GetFiles();
List<FileSystemItem>
fsItems = new List<FileSystemItem>(folders.Length + files.Length);
foreach (var file in files)
fsItems.Add(new FileSystemItem(file));
lstEmployees.DataSource = fsItems;
lstEmployees.DataBind();
}
#endregion
#region
"Datalist Methods"
protected void
lstEmployees_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item
| e.Item.ItemType == ListItemType.AlternatingItem)
{
FileSystemItem item = (FileSystemItem)e.Item.DataItem;
Image imgEmployee = (Image)e.Item.FindControl("imgEmployee");
if (imgEmployee != null)
{
imgEmployee.ImageUrl = Page.ResolveUrl("Images/"
+ item.Name);
}
}
}
#endregion
#region
"Event Handles"
protected void
Page_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
SetFilePath();
BindData();
}
}
catch
{
}
}
#endregion
}
}
VB.NET Code
'Visit http://www.laptrinhdotnet.com
for more ASP.NET Tutorials
Imports System.IO
Namespace DisplayImageInDataListfromFolder
Public Class _Default
Inherits System.Web.UI.Page
#Region "Private
Members"
Private FilePath As String = ""
#End Region
#Region "Private
Methods"
Private Sub
SetFilePath()
FilePath = MapPath("~/Images")
If Not Directory.Exists(FilePath) Then
Directory.CreateDirectory(FilePath)
End If
End Sub
Private Function
GetFullyQualifiedFolderPath(ByVal folderPath As String) As String
If folderPath.StartsWith("~")
Then
Return Server.MapPath(folderPath)
Else
Return folderPath
End If
End Function
#End Region
#Region "Bind Data"
Private Sub
BindData()
Dim currentDirInfo As
New DirectoryInfo(GetFullyQualifiedFolderPath(FilePath))
Dim folders = currentDirInfo.GetDirectories()
Dim files = currentDirInfo.GetFiles()
Dim fsItems As New List(Of FileSystemItem)(folders.Length
+ files.Length)
For Each file In files
fsItems.Add(New FileSystemItem(file))
Next
lstEmployees.DataSource
= fsItems
lstEmployees.DataBind()
End Sub
#End Region
#Region "Datalist
Methods"
Private Sub
lstEmployees_ItemDataBound(ByVal sender As Object, ByVal e As DataListItemEventArgs) Handles
lstEmployees.ItemDataBound
If (e.Item.ItemType = ListItemType.Item
Or e.Item.ItemType = ListItemType.AlternatingItem)
Then
Dim item As
FileSystemItem = CType(e.Item.DataItem,
FileSystemItem)
Dim imgEmployee As
Image = DirectCast(e.Item.FindControl("imgEmployee"), Image)
If imgEmployee IsNot
Nothing Then
imgEmployee.ImageUrl = Page.ResolveUrl("Images/"
& item.Name)
End If
End If
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
SetFilePath()
BindData()
End If
Catch ex As Exception
End Try
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.
Chúc các bạn thành công!
Quang Bình
No Comment to " Hiển thị danh sách ảnh trên Datalist từ thư mục "