News Ticker

Menu

Phóng to ảnh từ hình ảnh thu nhỏ trong Gridview

(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.
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 Customers trong SQL Server

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

STTTên trườngKiểu trườngGhi chú
1ItemIDIntTrường tự tăng
2Namenvarchar(35)
3Midfieldnvarchar(50)
4DateofbirthDatetime
5Countrynvarchar(50)
6Clubnvarchar(50)
7Heightnvarchar(50)
8Weightnvarchar(50)
9ImageURLnvarchar(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 @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.
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 DataTable FillTable(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 (ObjectPara p in Para)
                    {
                        adap.SelectCommand.Parameters.Add(new SqlParameter(p.Name, p.Value));
                    }
                }
                adap.Fill(tb);
                return tb;
            }
            catch
            {
                return null;
            }
        }
        #endregion
    }

    public class ObjectPara
    {
        string _name;

        object _Value;
        public ObjectPara(string Pname, 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 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

#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: 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
<%@ Page Title="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>
                    <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="PlayerID" width="100%">
                            <AlternatingRowStyle CssClass="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 void BindPlayers()
        {
            DataTable objBind = new DataTable();
            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 DataTable BindData(string Keyword)
        {
            SqlDataProvider objSQL = new SqlDataProvider();
            DataTable objBind = objSQL.FillTable("Pro_Players_List", new ObjectPara("@Keyword", Keyword.Trim()));
            return objBind;
        }

        #endregion

        #region "GridView Methods"

        protected void grvObject_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 void grvObject_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
        {
            grvObject.PageIndex = e.NewPageIndex;
            BindPlayers();
        }

        #endregion

        #region "Event Handles"

        protected void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    BindPlayers();
                }
            }
            catch
            {
            }
        }

        protected void cmdQuickSearch_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 Sub BindPlayers()
            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 Function BindData(ByVal Keyword As String) 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 Sub grvObject_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grvObject.PageIndexChanging
            grvObject.PageIndex = e.NewPageIndex
            BindPlayers()
        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
                    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.
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 " Phóng to ảnh từ hình ảnh thu nhỏ 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