(Showing Popup document on clicking Icon in Gridview) – Bài viết dưới đây sẽ hướng dẫn các bạn cách xây dựng hiển thị biểu tượng với những công việc có file đính kèm và khi kích vào tên công việc hoặc biểu tượng, 1 Popup sẽ hiển thị toàn bộ danh sách tài liệu thuộc công việc đã click.
- B1: Tạo CSDL Demo_Tasks trong SQL Server
STT | Tên trường | Kiểu trường | Ghi chú |
1 | TaskID | Int | Trường tự tăng |
2 | TaskName | nvarchar(250) | |
3 | StartDate | datetime | |
4 | EndDate | datetime | |
5 | IsFinish | bit | |
6 | CreatedDate | datetime |
- B3: Nhập dữ liệu cho bảng Tasks
- B4: Tạo Bảng Documents có cấu trúc phía dưới
- B4: Tạo Bảng Documents có cấu trúc phía dưới
STT | Tên trường | Kiểu trường | Ghi chú |
1 | DocumentID | Int | Trường tự tăng |
2 | TaskID | Int | |
3 | DocumentName | nvarchar(250) | |
4 | FileName | nvarchar(250) | |
5 | FileSize | nvarchar(50) | |
6 | Description | nvarchar(250) | |
7 | CreatedDate | datetime | |
8 | ModifiedDate | datetime |
- B5: Nhập dữ liệu cho bảng Documents
USE[Demo_Documents]
GO
CREATE PROCEDURE [dbo].[Pro_Tasks_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 *,(select count(*) from Documents where TaskID = Tasks.TaskID) as NumberOfDocument from Tasks'
set @strWhere =' Where 1=1 '
if @Keyword<>''
set @strWhere= @strWhere +' And (TaskName like N''%'+ @Keyword+'%'')'
if @SortField='CreatedDate'
Begin
set @strOrder =' Order by CreatedDate'
End
Else
Begin
set @strOrder =' Order by TaskName'
End
set @strSQL=@strSQL+@strWhere+@strOrder+ ' '+ @SortType
print @strSQL
exec sp_executesql @strSQL
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
- B7: 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 OpenPopupOnClickIconInGridview
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
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
Public FunctionGetRow(ByVal ProcName AsString, ByVal ParamArray Para() As ObjectPara) As DataRow
Try
Dim tb AsNew DataTable
Dim adap AsNew SqlDataAdapter(ProcName, _connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
For Eachp As ObjectParaIn 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 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
- B8: Download file attach.gif vào thư mục Images Project
- B9: Tạo thư mục UserControls, tạo file Popup_Documents.ascx trong thư mục vừa tạo
- B10: Mở file Popup_Documents. ascx dạng HTML và nhập mã HTML
<%@ ControlLanguage="vb"AutoEventWireup="false"CodeBehind="Popup_Documents.ascx.vb"Inherits="OpenPopupOnClickIconInGridview.UserControls.Popup_Documents"%>
<%@ RegisterTagPrefix="cc1"Assembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"%>
<asp:Panel ID="pnlpopup" runat="server" style="display:none">
<asp:UpdatePanel ID="updatePanelPopup"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<asp:Button id="cmdShowPopup"runat="server"style="display:none" />
<cc1:ModalPopupExtenderID="ModalPopupExtender_Popup"runat="server"TargetControlID="cmdShowPopup"X="550"Y="180"
PopupControlID="pnlpopup"CancelControlID="cmdCancel"BackgroundCssClass="ModalPopupBG"Drag="True"/>
<divclass="modal"style="width:850px;">
<divclass="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button"id="cmdClose"runat="server"causesvalidation="false"class="close"data-dismiss="modal"aria-hidden="true">x</button>
<h4 class="modal-title">
<asp:label id="lblHeader"runat="server"></asp:label>
</h4>
</div>
<div class="modal-body">
<table width="100%"cellpadding="2"cellspacing="3">
<tr>
<td>
<asp:label id="lblItemID"runat="server"Visible="false"></asp:label>
<asp:GridView ID="grvObject"runat="server"AllowPaging="true"PageSize="12"
CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"
BorderWidth="1"AutoGenerateColumns="false"DataKeyNames="DocumentID"width="100%">
<AlternatingRowStyleCssClass="GridStyle_AltRowStyle"/>
<HeaderStyleCssClass="GridStyle_HeaderStyle"/>
<RowStyleCssClass="GridStyle_RowStyle"/>
<pagerstylecssclass="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 HeaderText="DocumentName">
<ItemStylewidth="18%"/>
<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>
</div>
<div class="modal-footer">
<div class="btn-group">
<asp:LinkButton id="cmdCancel"runat="server"CssClass="btn btn-small" Text="Close" Causesvalidation="false">
</asp:LinkButton>
</div>
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel> - B11: Viết Code cho file Popup_Documents.ascx
Imports System.IO
Namespace OpenPopupOnClickIconInGridview.UserControls
Partial Class Popup_Documents
Inherits System.Web.UI.UserControl
#Region "Private Members"
Private _ItemID As Integer
Private filePath As String = ""
#End Region
#Region "Private Methods"
Private FunctionGetFileName(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 NotIsDBNull(objInfo("FileName")) Then
FileName = objInfo("FileName")
End If
End If
Return FileName
End Function
Private SubDownloadFile(ByVal filepath As String)
If filepath <> ""Then
Dim file AsNew 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 "Pulbic Methods"
Public Sub ShowPopup(ByVal ItemID As Integer)
lblItemID.Text = ItemID
BindDocument()
updatePanelPopup.Update()
ModalPopupExtender_Popup.Show()
End Sub
#End Region
#Region "Bind Data"
Private SubBindDocument()
Dim objBind As New DataTable
objBind = BindData()
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
grvObject.DataSource = objBind
grvObject.DataBind()
grvObject.Visible = True
lblHeader.Text = "Documents ("& objBind.Rows.Count & ")"
Else
grvObject.Visible = False
End If
updatePanelPopup.Update()
End If
End Sub
Private Function BindData() AsDataTable
Dim objSQL As New SqlDataProvider
If lblItemID.Text <> ""Then
ItemID = lblItemID.Text
End If
Dim objBind As DataTable = objSQL.FillTable("Pro_Documents_List", New ObjectPara("@Keyword", ""), _
New ObjectPara("@TaskID", ItemID), _
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 Casee.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 SubgrvObject_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) HandlesgrvObject.RowDataBound
Ife.Row.RowType = DataControlRowType.DataRow Then
Dim cmdDownload AsLinkButton = CType(e.Row.FindControl("cmdDownload"), LinkButton)
If cmdDownload IsNotNothing Then
cmdDownload.ToolTip = "Click to Download"
ScriptManager.GetCurrent(Page).RegisterPostBackControl(cmdDownload)
End If
End If
End Sub
Private SubgrvObject_PageIndexChanging(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewPageEventArgs) Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
BindDocument()
ModalPopupExtender_Popup.Show()
End Sub
#End Region
#Region "Properties"
Public PropertyItemID() As Integer
Get
Return _ItemID
End Get
Set(ByVal Value As Integer)
_ItemID = Value
End Set
End Property
#End Region
#Region "Event Handles"
Private SubcmdNo_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdCancel.Click
ModalPopupExtender_Popup.Hide()
End Sub
Private SubcmdClose_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdClose.ServerClick
ModalPopupExtender_Popup.Hide()
End Sub
#End Region
End Class
- B12: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ PageTitle="To open a popup on clicking Icon in Gridview" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" EnableEventValidation= "false" CodeBehind="Default.aspx.vb"Inherits="OpenPopupOnClickIconInGridview._Default"%>
<%@ RegisterTagPrefix="ModalPopup"TagName="Document"Src="~/UserControls/Popup_Documents.ascx"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"runat="server">
</asp:ScriptManager>
<ModalPopup:Document ID="ucDocument"runat="server"/>
<h3>
To open a popup on clicking Icon in Gridview
</h3>
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"cellspacing="3"width="100%">
<tr>
<td>
</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="TaskID"width="100%">
<AlternatingRowStyleCssClass="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 HeaderText="TaskName">
<ItemStyle width="22%" />
<ItemTemplate>
<asp:LinkButton id="cmdDownload" runat="server" CommandName="Download" CommandArgument='<%# Eval("TaskID") %>' text='<%# Eval("TaskName") %>'></asp:LinkButton>
<asp:Label ID="lblTask"runat="server"text='<%# Eval("TaskName") %>'>
</asp:Label>
<asp:ImageButton ID="cmdIconTask"runat="server"CommandName="Download"CommandArgument='<%# Eval("TaskID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="StartDate">
<ItemStyle HorizontalAlign="Center"Width="8%"></ItemStyle>
<ItemTemplate>
<asp:Label ID="lblStartDate"runat="server">
<%# FormatDate(Eval("StartDate"))%>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EndDate">
<ItemStyle HorizontalAlign="Center" Width="8%"></ItemStyle>
<ItemTemplate>
<asp:Label ID="lblEndDate"runat="server">
<%# FormatDate(Eval("EndDate"))%>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Finish">
<ItemStyle HorizontalAlign="Center"width="5%"/>
<ItemTemplate>
<asp:CheckBox id="chkFinish"runat="server"Checked='<%# FormatBoolean(Eval("IsFinish")) %>'></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="12%"DataField="CreatedDate"HeaderText="CreatedDate"/>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
- B13: Viết Code cho file Default.aspx
'Visit http://thuthuatlaptrinh.blogspot.com for more ASP.NET Tutorials
Namespace OpenPopupOnClickIconInGridview
Public Class _Default
Inherits System.Web.UI.Page
#Region "Private Methods"
Public FunctionFormatBoolean(ByVal KeyValue As Boolean) As String
Dim sKeyValue As Boolean
If KeyValue Then
sKeyValue = True
Else
sKeyValue = False
End If
Return sKeyValue
End Function
Public FunctionFormatDate(ByVal KeyValue As Object) As String
Dim sKeyValue As String = ""
If Not KeyValue Is System.DBNull.Value Then
sKeyValue = KeyValue.ToShortDateString
Else
sKeyValue = "-"
End If
Return sKeyValue
End Function
#End Region
#Region "Bind Data"
Private SubBindTask()
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 FunctionBindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Pro_Tasks_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 SubgrvObject_RowCommand(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewCommandEventArgs) Handles grvObject.RowCommand
Dim ItemID As Integer = Integer.Parse(e.CommandArgument)
Dim FileName As String = ""
Select Casee.CommandName.ToLower
Case "download"
With CType(ucDocument, OpenPopupOnClickIconInGridview.UserControls.Popup_Documents)
.ItemID = ItemID
.ShowPopup(ItemID)
End With
End Select
End Sub
Private SubgrvObject_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) HandlesgrvObject.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim NumberOfDocument As Integer = DataBinder.Eval(e.Row.DataItem, "NumberOfDocument")
Dim cmdDownload AsLinkButton = CType(e.Row.FindControl("cmdDownload"), LinkButton)
Dim cmdIconTask AsImageButton = CType(e.Row.FindControl("cmdIconTask"), ImageButton)
Dim lblTask AsLabel = CType(e.Row.FindControl("lblTask"), Label)
If NotcmdDownload Is NothingThen
If NumberOfDocument > 0 Then
cmdDownload.ToolTip = "Click to Download"
cmdDownload.Visible = True
cmdIconTask.Visible = True
lblTask.Visible = False
cmdIconTask.ImageUrl = Page.ResolveUrl("~/Images/Attach.gif")
Else
cmdDownload.Visible = False
lblTask.Visible = True
cmdIconTask.Visible = False
End If
End If
End If
End Sub
Private SubgrvObject_PageIndexChanging(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewPageEventArgs) Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
BindTask()
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
'Default Submit Button
Page.Form.DefaultButton = cmdQuickSearch.UniqueID
BindTask()
End If
Catch ex As Exception
End Try
End Sub
Private SubcmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdQuickSearch.Click
BindTask()
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
0 comments Blogger 0 Facebook
Post a Comment