(Làm thế nào để hiển thị hình ảnh trên Tooltip trong Gridview) – Có rất nhiều cách để xem nhanh thông tin của một đối tượng như: hiển thị Tooltip, bật Popup. Với Tooltip thì chỉ cần đưa chuột vào 1 đối tượng nào đó lập tức Tooltip xuất hiện, còn với Popup người dùng sẽ phải thêm 1 thao tác đó là click. Bài viết dưới đây sẽ hướng dẫn các bạn cách xây dựng Tooltip trong Gridview, chỉ cần đưa chuột vào tên cầu thủ, ảnh gốc của cầu thủ đó sẽ xuất hiện trên Tooltip.

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 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.
Imports System.Data.SqlClient
Imports System.Data

Namespace ShowImageToolTipOnMouseoverInGridview

    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 Not Para Is Nothing Then
                    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

#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

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: Tạo thư mục Js trong Project, Download file  jquery.tooltip.min.js và Copy file vào thư mục Js

B8: Mở file Default.aspx dưới dạng HTML và  nhập mã HTML
<%@ PageTitle="Show Image as ToolTip on Mouseover in GridView" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="ShowImageToolTipOnMouseoverInGridview._Default"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <script src="http://code.jquery.com/jquery-1.8.2.js"type="text/javascript"></script>
    <script src="js/jquery.tooltip.min.js"type="text/javascript"></script>
    <script type="text/javascript">
        function InitializeToolTip() {
            $(".ShowToolTip").tooltip({
                track: true,
                delay: 0,
                showURL: false,
                fade: 100,
                bodyHandler: function () {
                    return $($(this).next().html());
                },
                showURL: false
            });
        }
    </script>
    <script type="text/javascript">
        function pageLoad() {
            InitializeToolTip();
        };
    </script>
    <asp:ScriptManager ID="ScriptManager1"runat="server">
    </asp:ScriptManager>
    <h3>
        Show Image as ToolTip on Mouseover 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") %>' class="ShowToolTip"runat="server"></asp:Label>
                                        <div id="tooltip"style="display: none;">
                                            <asp:Image ID="imgPlayer" ImageUrl='<%#Eval("ImageURL") %>' runat="server"/>
                                         </div>
                                    </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"ImageUrl='<%#Eval("ImageURL")%>' AlternateText='<%# Eval("ImageURL") %>' runat="server"/>
                                    </ItemTemplate>                          
                                </asp:TemplateField>                               
                            </Columns>                              
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

B9: 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 ShowImageToolTipOnMouseoverInGridview
{
    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 void grvObject_RowDataBound(object sender, GridViewRowEventArgse)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DateTime Dateofbirth = Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, "Dateofbirth"));

                LabellblDateofbirth = (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 ShowImageToolTipOnMouseoverInGridview

    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 SubcmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdQuickSearch.Click
            BindPlayers()
        End Sub

#End Region

    End Class

End Namespace

Bây giờ chạy Project, và mỗi khi di chuột vào các giá trị ở cột Name 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

0 comments Blogger 0 Facebook

Post a Comment

 
lập trình đốt nét © 2013. All Rights Reserved. Powered by Blogger
Top