(Sử dụng jquery để phóng to ảnh trong Gridview) – Bạn đang có 1 danh sách nhân sự, ngoài thông tin ký tự, danh sách này còn có cả hình ảnh đại diện cho từng cán bộ. Bạn muốn hiển thị danh sách này trên Gridview gồm cả ký tự và hình ảnh. Tuy nhiên đối với hình ảnh nếu để nhỏ quá thì khó quan sát, còn nếu để to quá thì lại tốn diện tích. Vậy có cách nào để vừa không mất diện tích mà lại có thể xem hình ảnh ở dạng gốc không? Bài viết dưới đây sẽ hướng dẫn các bạn giải quyết vấn đề này, các hình ảnh ở mỗi dòng ở dạng Thumbnail và mỗi lần Click vào hình ảnh một cửa sổ Popup sẽ xuất hiện.
- B1: Tạo CSDL Customers trong SQL Server
- B2: Tạo Bảng Players có cấu trúc phía dưới
STT | Tên trường | Kiểu trường | Ghi chú |
1 | ItemID | Int | Trường tự tăng |
2 | Name | nvarchar(35) | |
3 | Midfield | nvarchar(50) | |
4 | Dateofbirth | Datetime | |
5 | Country | nvarchar(50) | |
6 | Club | nvarchar(50) | |
7 | Height | nvarchar(50) | |
8 | Weight | nvarchar(50) | |
9 | ImageURL | nvarchar(200) |
- B3: Nhập dữ liệu cho bảng Players
- B4: Tạo stored procedure trong SQL Server
CREATE PROCEDURE [dbo].[Pro_Players_List]
@Keyword nvarchar(250)
AS
declare@strSQL nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)
set @strSQL= 'Select * from Players'
set @strWhere =' Where 1=1 '
if @Keyword<>''
set @strWhere= @strWhere +' And (Name like N''%'+@Keyword+'%''
Or Midfield like N''%' +@Keyword+'%'' Or Country like N''%' +@Keyword+'%''
Or Club like N''%' +@Keyword+'%'')'
set @strOrder =' Order by Name'
set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql@strSQLGo
- 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.
C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace BindImageInGridview
{
public class SqlDataProvider
{
#region"Membres Prives"
private string_connectionString;
#endregion
#region"Constructeurs"
public SqlDataProvider()
{
try
{
_connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
}
catch
{
}
}
#endregion
#region"Proprietes"
public string ConnectionString
{
get { return_connectionString; }
}
#endregion
#region"Functions"
public DataTableFillTable(string ProcName, params ObjectPara[] Para)
{
try
{
DataTable tb = new DataTable();
SqlDataAdapter adap = new SqlDataAdapter(ProcName, _connectionString);
adap.SelectCommand.CommandType = CommandType.StoredProcedure;
if (Para != null)
{
foreach (ObjectParap in Para)
{
adap.SelectCommand.Parameters.Add(new SqlParameter(p.Name, p.Value));
}
}
adap.Fill(tb);
returntb;
}
catch
{
return null;
}
}
#endregion
}
public class ObjectPara
{
string _name;
object _Value;
public ObjectPara(stringPname, object PValue)
{
_name = Pname;
_Value = PValue;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public object Value
{
get{ return _Value; }
set { _Value = value; }
}
}
}
VB.NET Code
Imports System.Data.SqlClient
Imports System.Data
Namespace BindImageInGridview
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
ForEach 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
#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
Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config
- B6: Download các file ảnh tại đây, Copy ảnh lần lượt vào các thư mục Images của Project
- B7: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ PageTitle="Display image Thumbnail from database in GridView" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="BindImageInGridview._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.23/jquery-ui.min.js"type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/base/jquery-ui.css"rel="stylesheet"type="text/css"/>
<script type="text/javascript">
$(function () {
$('[id*=imgPlayer]').bind('click', function() {
$("[id*=imgPreview]").attr('src', $(this).attr('alt'));
$("#divImage").dialog({
title: "Preview Image",
modal: true,
resizable: false,
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
});
});
</script>
<asp:ScriptManager ID="ScriptManager1"runat="server">
</asp:ScriptManager>
<h3>
Display image Thumbnail from database in GridView
</h3>
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"cellspacing="3"width="100%">
<tr>
<td>
<h4>
<asp:Label ID="lblTotal"runat="server"Visible="false"></asp:Label>
</h4>
</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="PlayerID"width="100%">
<AlternatingRowStyleCssClass="GridStyle_AltRowStyle"/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"/>
<RowStyle CssClass="GridStyle_RowStyle"/>
<pagerstyle cssclass="GridStyle_pagination"/>
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemStyle HorizontalAlign="Left"width="15%"/>
<ItemTemplate>
<asp:Label ID="lblName"Text='<%# Eval("Name") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Midfield">
<ItemStyle HorizontalAlign="Left"width="12%"/>
<ItemTemplate>
<asp:Label ID="lblMidfield"Text='<%# Eval("Midfield") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dateofbirth">
<ItemStyle HorizontalAlign="Center"width="10%"/>
<ItemTemplate>
<asp:Label ID="lblDateofbirth"Text='<%# Eval("Dateofbirth").ToShortDateString %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblCountry"Text='<%# Eval("Country") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Club">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblClub"Text='<%# Eval("Club") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Height">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblHeight"Text='<%# Eval("Height") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Weight">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblWeight"Text='<%# Eval("Weight") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image">
<ItemStyle HorizontalAlign="Center"width="3%"/>
<ItemTemplate>
<asp:Image ID="imgPlayer"Width="40"style="cursor: pointer" ImageUrl='<%#Eval("ImageURL")%>' AlternateText='<%# Eval("ImageURL") %>' runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
<div id="divImage"style="display: none;">
<asp:Image ID="imgPreview"runat="server"/>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
- B8: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace BindImageInGridview
{
public partial class _Default : System.Web.UI.Page
{
#region"Bind Data"
private voidBindPlayers()
{
DataTable objBind = newDataTable();
int iTotal = 0;
objBind = BindData(txtSearch.Text);
if (objBind != null)
{
if (objBind.Rows.Count > 0)
{
iTotal = objBind.Rows.Count;
grvObject.DataSource = objBind;
grvObject.DataBind();
trMessage.Visible = false;
grvObject.Visible = true;
lblTotal.Visible = true;
lblTotal.Text = "Total " + iTotal + " records";
}
else
{
trMessage.Visible = true;
lblTotal.Visible = false;
grvObject.Visible = false;
}
}
updatePanel.Update();
}
private DataTableBindData(string Keyword)
{
SqlDataProvider objSQL = newSqlDataProvider();
DataTable objBind = objSQL.FillTable("Pro_Players_List", new ObjectPara("@Keyword", Keyword.Trim()));
return objBind;
}
#endregion
#region"GridView Methods"
protected voidgrvObject_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DateTime Dateofbirth = Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, "Dateofbirth"));
Label lblDateofbirth = (Label)e.Row.FindControl("lblDateofbirth");
if(lblDateofbirth != null)
{
if (Dateofbirth != null)
{
lblDateofbirth.Text = Dateofbirth.ToString("MM/dd/yyyy");
}
else
{
lblDateofbirth.Text = "-";
}
}
}
}
protected voidgrvObject_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgse)
{
grvObject.PageIndex = e.NewPageIndex;
BindPlayers();
}
#endregion
#region"Event Handles"
protected voidPage_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
BindPlayers();
}
}
catch
{
}
}
protected voidcmdQuickSearch_Click(object sender, System.EventArgs e)
{
BindPlayers();
}
#endregion
}
}VB.NET Code
Imports System.IO
Namespace BindImageInGridview
Public Class _Default
Inherits System.Web.UI.Page
#Region "Bind Data"
Private SubBindPlayers()
Dim objBind As New DataTable
Dim iTotal As Integer = 0
objBind = BindData(txtSearch.Text)
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
iTotal = objBind.Rows.Count
grvObject.DataSource = objBind
grvObject.DataBind()
trMessage.Visible = False
grvObject.Visible = True
lblTotal.Visible = True
lblTotal.Text = "Total "& iTotal & " records"
Else
trMessage.Visible = True
lblTotal.Visible = False
grvObject.Visible = False
End If
End If
updatePanel.Update()
End Sub
Private FunctionBindData(ByVal Keyword AsString) As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Pro_Players_List", New ObjectPara("@Keyword", Keyword.Trim))
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
BindPlayers()
End Sub
#End Region
#Region "Event Handles"
Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
Try
If Page.IsPostBack = False Then
BindPlayers()
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
BindPlayers()
End Sub
#End Region
End Class
End Namespace
Bây giờ chạy Project, và mỗi khi kích vào các giá trị ở cột Image một Popup sẽ xuất hiện như ảnh phía dưới.
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment