(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.

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: 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 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 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 FunctionRunSQL(ByVal ProcName AsString, ByVal ParamArray Para() As ObjectPara) As Object
            Try
                Dim _cnn AsNew SqlConnection(_connectionString)
                _cnn.Open()

                Dim cmd AsNew SqlCommand(ProcName, _cnn)
                cmd.CommandType = CommandType.StoredProcedure
                For Eachp As ObjectParaIn 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 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

    Public Class MyEventArgs
        Inherits EventArgs

        Private Name As String
        Private MyId As String

        Public PropertySelectedName() As String
            Get
                ReturnName
            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-imageurl(Images/lt.gif);
    background-positioncenter center;
    height16px;
    width16px;
}

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.

<%@ ControlLanguage="vb"AutoEventWireup="false"CodeBehind="Popup_OrderDetails.ascx.vb"Inherits="MasterDetailInGridView.UserControls.Popup_OrderDetails"%>
<%@ 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="620"Y="150"
                PopupControlID="pnlpopup"CancelControlID="cmdCancel"BackgroundCssClass="ModalPopupBG"Drag="True"/>
                <divclass="modal"style="width:700px;">
                    <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"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%">
                                                    <AlternatingRowStyleCssClass="GridStyle_AltRowStyle"/>
                                                    <HeaderStyleCssClass="GridStyle_HeaderStyle"/>
                                                    <RowStyleCssClass="GridStyle_RowStyle"/>
                                                    <pagerstylecssclass="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">
                                                                  <ItemStyleHorizontalAlign="Right"width="10%"/>   
                                                            <ItemTemplate>
                                                                <asp:Label ID="lblUnitPrice" Text='<%# Eval("UnitPrice") %>' runat="server"></asp:Label>
                                                            </ItemTemplate>                          
                                                        </asp:TemplateField>  
                                                        <asp:TemplateField HeaderText="Quantity">
                                                                  <ItemStyleHorizontalAlign="Right"width="8%"/>   
                                                            <ItemTemplate>
                                                                <asp:Label ID="lblQuantity"Text='<%# Eval("Quantity") %>' runat="server"></asp:Label>
                                                            </ItemTemplate>                          
                                                        </asp:TemplateField>   
                                                        <asp:TemplateField HeaderText="Discount">
                                                                  <ItemStyleHorizontalAlign="Right"width="8%"/>   
                                                            <ItemTemplate>
                                                                <asp:Label ID="lblDiscount"Text='<%# Eval("Discount") %>' runat="server"></asp:Label>
                                                            </ItemTemplate>                          
                                                        </asp:TemplateField>  
                                                        <asp:TemplateField HeaderText="ExtendedPrice">
                                                                 <ItemStyleHorizontalAlign="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>&nbsp;&nbsp;<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 SubBindOrderDetail()
            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 FunctionBindData() As DataTable
            DimobjSQL 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 SubgrvObject_PageIndexChanging(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewPageEventArgs) Handles grvObject.PageIndexChanging
            grvObject.PageIndex = e.NewPageIndex
            ModalPopupExtender_Popup.Show()
            BindOrderDetail()
        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

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

<%@ PageTitle="Build Master Detail GridView using ModalPopupExtender in ASP.Net" Language="vb"MasterPageFile="~/Site.Master"AutoEventWireup="false"CodeBehind="Default.aspx.vb"Inherits="MasterDetailInGridView._Default"%>
<%@ RegisterTagPrefix="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%">
                <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="OrderID"width="100%">
                            <AlternatingRowStyleCssClass="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 SubBindOrder()
            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 FunctionBindData() 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 SubgrvObject_RowCommand(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewCommandEventArgs) Handles grvObject.RowCommand
            Dim ItemID As Integer = Integer.Parse(e.CommandArgument)
            Select Casee.CommandName.ToLower
                Case "view"
                    With CType(ucOrderDetails, MasterDetailInGridView.UserControls.Popup_OrderDetails)
                        .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 cmdCustomer AsLinkButton = DirectCast(e.Row.FindControl("cmdCustomer"), LinkButton)
                If NotcmdCustomer Is NothingThen
                    cmdCustomer.ToolTip = "View Order Details"
                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
            BindOrder()
        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
                    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.

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