Tạo Master Detail cho GridView sử dụng ModalPopupExtender trong Asp.net
(Tạo Master Detail cho Gridview) – Chức năng Master Detail sẽ cho phép người sử dụng quan sát, đánh giá dữ liệu một cách dễ dàng và trực quan nhất. Thông thường để xem các sản phẩm trong 1 đơn hàng, người sử dụng sẽ phải kích vào thông tin 1 đơn hàng, một màn hình mới sẽ xuất hiện hiển thị danh sách các sản phẩm của đơn hàng đó. Và nếu muốn xem thông tin đơn hàng khác, người sử dụng sẽ phải kích nút quay lại màn hình chính. Nhưng với Master Detail không phải mất nhiều thao tác để xem các đơn hàng mong muốn. Bài viết dưới đây sẽ hướng dẫn các bạn cách xây dựng chức năng Master Detail sử dụng ModalPopupExtender trong Gridview.
- B1: Download CSDL Northwind
- B1: Download CSDL Northwind
- B2: 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 MasterDetailInGridView
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 sql As
String) As DataTable
Try
Dim tb As
New DataTable
Dim adap As
New SqlDataAdapter(sql,
_connectionString)
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
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
Public Function
RunSQL(ByVal ProcName As
String, ByVal ParamArray Para() As ObjectPara) As Object
Try
Dim _cnn As
New SqlConnection(_connectionString)
_cnn.Open()
Dim cmd As
New SqlCommand(ProcName,
_cnn)
cmd.CommandType = CommandType.StoredProcedure
For Each
p As ObjectPara
In Para
cmd.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
Return cmd.ExecuteScalar
Catch ex As Exception
Return Nothing
End Try
End Function
Public Function
GetRow(ByVal ProcName As
String, ByVal ParamArray Para() As ObjectPara) As DataRow
Try
Dim tb As
New DataTable
Dim adap As
New SqlDataAdapter(ProcName,
_connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
For Each
p As ObjectPara
In 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 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
Public Class MyEventArgs
Inherits EventArgs
Private Name As String
Private MyId As String
Public Property
SelectedName() As String
Get
Return
Name
End Get
Set(ByVal value As String)
Name = value
End Set
End Property
Public Property Id() As String
Get
Return MyId
End Get
Set(ByVal value As String)
MyId = 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
- B3: Download thư viện AjaxControlToolkit tại địa chỉ: Download
- B4: Giải nén AjaxControlToolkit.Binary.NET4, và References Ajaxcontroltoolkit.dll trong thư mục vừa giải nén vào Project.
- B5: Download thư viện Bootstrap, giải nén và copy file bootstrap.css vào thư mục Styles trong Project
- B6: Tạo file Button.css trong thư mục Styles và nhập các thông tin phía dưới
.icon-close {
background-image: url(Images/lt.gif);
background-position: center center;
height: 16px;
width: 16px;
}
- B7: Download các file ảnh tại đây, Copy ảnh vào thư mục
- lt.gif vào thư mục Styles\Images
- B8: Tạo thư mục UserControls và thêm file Popup_OrderDetails.ascx, mở file dưới dạng HTML và nhập thông tin phía dưới.
<%@ Control
Language="vb"
AutoEventWireup="false"
CodeBehind="Popup_OrderDetails.ascx.vb"
Inherits="MasterDetailInGridView.UserControls.Popup_OrderDetails"
%>
<%@ Register
TagPrefix="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:ModalPopupExtender
ID="ModalPopupExtender_Popup"
runat="server"
TargetControlID="cmdShowPopup"
X="620"
Y="150"
PopupControlID="pnlpopup"
CancelControlID="cmdCancel"
BackgroundCssClass="ModalPopupBG"
Drag="True"
/>
<div
class="modal"
style="width:700px;">
<div
class="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"
Text="Orders
Detail"></asp:label>
</h4>
</div>
<div class="modal-body">
<table width="100%"
cellpadding="2"
cellspacing="3">
<tr>
<td>
<asp:Label ID="lblItemID"
Visible="false"
runat="server"/>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="grvObject"
runat="server"
AllowPaging="true"
PageSize="8"
CssClass="GridStyle"
BorderColor="#cbcbcb"
BorderStyle="solid"
BorderWidth="1"
AutoGenerateColumns="false"
width="100%">
<AlternatingRowStyle
CssClass="GridStyle_AltRowStyle"
/>
<HeaderStyle
CssClass="GridStyle_HeaderStyle"
/>
<RowStyle
CssClass="GridStyle_RowStyle"
/>
<pagerstyle
cssclass="GridStyle_pagination"
/>
<Columns>
<asp:TemplateField HeaderText="ProductName">
<ItemStyle width="25%" />
<ItemTemplate>
<asp:Label ID="lblProductName"
Text='<%# Eval("ProductName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UnitPrice">
<ItemStyle
HorizontalAlign="Right"
width="10%"
/>
<ItemTemplate>
<asp:Label ID="lblUnitPrice" Text='<%# Eval("UnitPrice") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemStyle
HorizontalAlign="Right"
width="8%"
/>
<ItemTemplate>
<asp:Label ID="lblQuantity"
Text='<%# Eval("Quantity") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Discount">
<ItemStyle
HorizontalAlign="Right"
width="8%"
/>
<ItemTemplate>
<asp:Label ID="lblDiscount"
Text='<%# Eval("Discount") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ExtendedPrice">
<ItemStyle
HorizontalAlign="Right"
width="10%"
/>
<ItemTemplate>
<asp:Label ID="lblExtendedPrice"
Text='<%# Eval("ExtendedPrice") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</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" Causesvalidation="false">
<i class="icon-close"></i> <asp:label id="lblClose" runat="server" Text="Close"></asp:label>
</asp:LinkButton>
</div>
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel> - B9: Nhập Code phía dưới cho file Popup_OrderDetails.ascx
Namespace MasterDetailInGridView.UserControls
Partial Class Popup_OrderDetails
Inherits System.Web.UI.UserControl
#Region "Private
Members"
Private _ItemID As Integer
#End Region
#Region "Pulbic
Methods"
Public Sub ShowPopup(ByVal ItemID As Integer)
lblItemID.Text = ItemID
grvObject.PageIndex = 0
BindOrderDetail()
updatePanelPopup.Update()
ModalPopupExtender_Popup.Show()
End Sub
#End Region
#Region "Bind Data"
Private Sub
BindOrderDetail()
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
updatePanelPopup.Update()
Else
grvObject.Visible = False
End If
End If
End Sub
Public Function
BindData() As DataTable
Dim
objSQL As New SqlDataProvider
If lblItemID.Text <> ""
Then
ItemID = lblItemID.Text
End If
Dim objBind As DataTable = objSQL.FillTable("CustOrdersDetail", New ObjectPara("@OrderID", ItemID))
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
ModalPopupExtender_Popup.Show()
BindOrderDetail()
End Sub
#End Region
#Region "Properties"
Public Property
ItemID() As Integer
Get
Return _ItemID
End Get
Set(ByVal Value As Integer)
_ItemID = Value
End Set
End Property
#End Region
#Region "Event
Handles"
Private Sub
cmdNo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdCancel.Click
ModalPopupExtender_Popup.Hide()
End Sub
Private Sub
cmdClose_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdClose.ServerClick
ModalPopupExtender_Popup.Hide()
End Sub
#End Region
End Class
End Namespace
- B10: Mở file Site.Master dưới dạng HTML và gắn thêm các css cho Project ngay phía dưới thẻ <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Styles/GridStyle.css" rel="stylesheet" type="text/css" />
<link href="~/Styles/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="~/Styles/Button.css" rel="stylesheet" type="text/css" />- B11: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ Page
Title="Build
Master Detail GridView using ModalPopupExtender in ASP.Net" Language="vb"
MasterPageFile="~/Site.Master"
AutoEventWireup="false"
CodeBehind="Default.aspx.vb"
Inherits="MasterDetailInGridView._Default"
%>
<%@ Register
TagPrefix="ModalPopup"
TagName="ListRecord"
Src="~/UserControls/Popup_OrderDetails.ascx"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"
runat="server">
</asp:ScriptManager>
<h3>
Build
Master Detail GridView using ModalPopupExtender in ASP.Net
</h3>
<br />
<ModalPopup:ListRecord ID="ucOrderDetails"
runat="server"
/>
<asp:UpdatePanel ID="updatePanel"
runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"
cellspacing="3"
width="100%">
<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="OrderID"
width="100%">
<AlternatingRowStyle
CssClass="GridStyle_AltRowStyle"
/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"
/>
<RowStyle CssClass="GridStyle_RowStyle"
/>
<pagerstyle cssclass="GridStyle_pagination"
/>
<Columns>
<asp:TemplateField HeaderText="Customer">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:LinkButton id="cmdCustomer"
runat="server"
CausesValidation="False"
CommandName="View"
CommandArgument='<%# Eval("OrderID") %>' text='<%# Eval("CustomerID") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OrderDate">
<ItemStyle HorizontalAlign="Center"
width="10%"
/>
<ItemTemplate>
<asp:Label ID="lblOrderDate"
Text='<%# Eval("OrderDate").ToShortDateString %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RequiredDate">
<ItemStyle HorizontalAlign="Center"
width="10%"
/>
<ItemTemplate>
<asp:Label ID="lblRequiredDate"
Text='<%# Eval("RequiredDate").ToShortDateString %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ShippedDate">
<ItemStyle HorizontalAlign="Center"
width="10%"
/>
<ItemTemplate>
<asp:Label ID="lblShippedDate"
Text='<%# Eval("ShippedDate").ToShortDateString %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ShipName">
<ItemStyle width="15%" />
<ItemTemplate>
<asp:Label ID="lblShipName"
Text='<%# Eval("ShipName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ShipAddress">
<ItemStyle width="18%" />
<ItemTemplate>
<asp:Label ID="lblShipAddress"
Text='<%# Eval("ShipAddress") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>- B12: Viết Code cho file Default.aspx
Imports System.IO
Namespace MasterDetailInGridView
Public Class _Default
Inherits System.Web.UI.Page
#Region "Bind Data"
Private Sub
BindOrder()
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
updatePanel.Update()
Else
trMessage.Visible = True
grvObject.Visible = False
End If
End If
End Sub
Private Function
BindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Select Orders.* From Orders")
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)
Select Case
e.CommandName.ToLower
Case "view"
With CType(ucOrderDetails,
MasterDetailInGridView.UserControls.Popup_OrderDetails)
.ItemID = ItemID
.ShowPopup(ItemID)
End With
End Select
End Sub
Private Sub
grvObject_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles
grvObject.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow)
Then
Dim cmdCustomer As
LinkButton = DirectCast(e.Row.FindControl("cmdCustomer"), LinkButton)
If Not
cmdCustomer Is Nothing
Then
cmdCustomer.ToolTip = "View Order
Details"
End If
End If
End Sub
Private Sub
grvObject_PageIndexChanging(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewPageEventArgs)
Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
BindOrder()
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
BindOrder()
End If
Catch ex As Exception
End Try
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 Customer 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
No Comment to " Tạo Master Detail cho GridView sử dụng ModalPopupExtender trong Asp.net "