(Tạo chức năng Master Detail cho GridView) – Ví dụ dưới đây sẽ hướng dẫn các bạn cách xây dựng chức năng Master Detail cho Gridview. Mô hình sử dụng sẽ là mối quan hệ giữa đơn hàng và danh sách các sản phẩm của đơn hàng. Khi kích vào 1 dòng đơn hàng, toàn bộ danh sách các sản phẩm của đơn hàng được chọn sẽ xuất hiện. Dưới đây là các bước thực hiện.

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 MasterDetailDataInGridview

    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
                Dimadap As New 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

#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

B3: Download các file ảnh tại đây, Copy các ảnh vào thư mục Images của Project

B4: Tạo thư mục UserControls và thêm file OrderDetails.ascx, mở file dưới dạng HTML và nhập mã HTML.

<%@ ControlLanguage="vb"AutoEventWireup="false"CodeBehind="OrderDetails.ascx.vb"Inherits="MasterDetailDataInGridview.UserControls.OrderDetails"%>

<asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
    <asp:Label ID="lblItemID"Visible="false"runat="server"/>
    <asp:GridView ID="grvObject"runat="server"
        CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"
        BorderWidth="1"AutoGenerateColumns="false"width="100%">
        <AlternatingRowStyleCssClass="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>
</ContentTemplate>
</asp:UpdatePanel>

B5: Nhập Code phía dưới cho file OrderDetails.ascx

C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Web.UI.WebControls;

namespace MasterDetailDataInGridview.UserControls
{
    partial class OrderDetails : System.Web.UI.UserControl
    {

        #region"Private Members"

        private int _ItemID;

        #endregion

        #region"Bind Data"

        public voidBindOrderDetail(int ItemID)
        {
            DataTable objBind = newDataTable();
            lblItemID.Text = ItemID.ToString();
            objBind = BindData();
            if (objBind != null)
            {
                if (objBind.Rows.Count > 0)
                {
                    grvObject.DataSource = objBind;
                    grvObject.DataBind();
                    grvObject.Visible = true;
                }
                else
                {
                    grvObject.Visible = false;
                }
                updatePanel.Update();
            }
        }

        public DataTableBindData()
        {
            SqlDataProvider objSQL = newSqlDataProvider();
            if (!string.IsNullOrEmpty(lblItemID.Text))
            {
                ItemID =Convert.ToInt32(lblItemID.Text);
            }

            DataTable objBind = objSQL.FillTable("CustOrdersDetail", new ObjectPara("@OrderID", ItemID));
            return objBind;
        }

        #endregion

        #region"Properties"

        public int ItemID
        {
            get { return _ItemID; }
            set { _ItemID = value; }
        }

        #endregion
    }
}

VB.NET Code
Namespace MasterDetailDataInGridview.UserControls
    Partial Class OrderDetails
        Inherits System.Web.UI.UserControl

#Region "Private Members"

        Private _ItemID As Integer

#End Region

#Region "Bind Data"

        Public SubBindOrderDetail(ByVal ItemID As Integer)
            Dim objBind As New DataTable
            lblItemID.Text = ItemID
            objBind = BindData()
            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then
                    grvObject.DataSource = objBind
                    grvObject.DataBind()
                    grvObject.Visible = True

                Else
                    grvObject.Visible = False
                End If
                updatePanel.Update()
            End If
        End Sub

        Public FunctionBindData() 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 "Properties"

        Public PropertyItemID() As Integer
            Get
                Return _ItemID
            End Get
            Set(ByVal Value As Integer)
                _ItemID = Value
            End Set
        End Property

#End Region

    End Class

End Namespace

- B6: Mở file Default.aspx dưới dạng HTML và  nhập mã HTML

<%@ PageTitle="Display inline Master Detail data in a Asp.Net Gridview" Language="vb"MasterPageFile="~/Site.Master"AutoEventWireup="false"CodeBehind="Default.aspx.vb"Inherits="MasterDetailDataInGridview._Default"%>
<%@ RegisterTagPrefix="OrderDetail"TagName="ListRecord"Src="~/UserControls/OrderDetails.ascx"%>

<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 type="text/javascript">
        $("[src*=Expand]").live("click", function() {
            $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
            $(this).attr("src", "Images/Collapse.jpg");
        });
        $("[src*=Collapse]").live("click", function() {
            $(this).attr("src", "Images/Expand.jpg");
            $(this).closest("tr").next().remove();
        });
    </script>
    <asp:ScriptManager ID="ScriptManager1"runat="server">
    </asp:ScriptManager>
    <h3>
        Display inline Master Detail data in a Asp.Net Gridview
    </h3>
    <br />
    <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>
                                <ItemStyle HorizontalAlign="Center"width="1%"/> 
                                    <ItemTemplate>
                                        <img alt = "OrderDetails" style="cursor: pointer" src="Images/Expand.jpg" />
                                        <asp:Panel ID="pnlOrders"runat="server"Style="display: none">
                                            <OrderDetail:ListRecord ID="ucOrderDetails"runat="server"/>
                                        </asp:Panel>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Customer"ItemStyle-Width="10%">
                                    <ItemTemplate>
                                        <asp:Label ID="lblCustomerID"Text='<%# Eval("CustomerID") %>' runat="server"></asp:Label>
                                    </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>

- B7: 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 MasterDetailDataInGridview
{
    public partial class _Default : System.Web.UI.Page
    {

        #region"Bind Data"

        private void BindOrder()
        {
            DataTable objBind = newDataTable();
            objBind = BindData();

            if (objBind != null)
            {
                if (objBind.Rows.Count > 0)
                {
                    grvObject.DataSource = objBind;
                    grvObject.DataBind();
                    trMessage.Visible = false;
                    grvObject.Visible = true;
                    updatePanel.Update();
                }
                else
                {
                    trMessage.Visible = true;
                    grvObject.Visible = false;
                }
            }
        }

        private DataTableBindData()
        {
            SqlDataProvider objSQL = newSqlDataProvider();
            DataTable objBind = objSQL.FillTable("Select Orders.* From Orders");
            return objBind;
        }

        #endregion

        #region"GridView Methods"

        protected voidgrvObject_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DateTime OrderDate = Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, "OrderDate"));
                DateTime RequiredDate = Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, "RequiredDate"));
                DateTime ShippedDate = Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, "ShippedDate"));

                int OrderID =Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "OrderID"));
                MasterDetailDataInGridview.UserControls.OrderDetailsucOrderDetails = (MasterDetailDataInGridview.UserControls.OrderDetails)e.Row.FindControl("ucOrderDetails");
                if (ucOrderDetails != null)
                {
                    if(OrderID != -1 & OrderID != 0)
                    {
                        ucOrderDetails.BindOrderDetail(OrderID);
                    }
                }
                Label lblOrderDate = (Label)e.Row.FindControl("lblOrderDate");
                if(lblOrderDate != null)
                {
                    if (OrderDate != null)
                    {
                        lblOrderDate.Text = OrderDate.ToString("MM/dd/yyyy");
                    }
                    else
                    {
                        lblOrderDate.Text = "-";
                    }
                }
                Label lblRequiredDate = (Label)e.Row.FindControl("lblRequiredDate");
                if (lblRequiredDate != null)
                {
                    if (RequiredDate != null)
                    {
                        lblRequiredDate.Text = RequiredDate.ToString("MM/dd/yyyy");
                    }
                    else
                    {
                        lblRequiredDate.Text = "-";
                    }
                }
                Label lblShippedDate = (Label)e.Row.FindControl("lblShippedDate");
                if (lblShippedDate != null)
                {
                    if(ShippedDate != null)
                    {
                        lblShippedDate.Text = ShippedDate.ToString("MM/dd/yyyy");
                    }
                    else
                    {
                        lblShippedDate.Text = "-";
                    }
                }
            }
        }

        protected voidgrvObject_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgse)
        {
            grvObject.PageIndex = e.NewPageIndex;
            BindOrder();
        }

        #endregion

        #region"Event Handles"

        protected voidPage_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    BindOrder();
                }
            }
            catch
            {
            }
        }

        #endregion
    }
}

VB.NET Code
‘Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Imports System.IO

Namespace MasterDetailDataInGridview

    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_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) HandlesgrvObject.RowDataBound
            If (e.Row.RowType = DataControlRowType.DataRow) Then
                Dim OrderID AsInteger = DataBinder.Eval(e.Row.DataItem, "OrderID")
                Dim ucOrderDetails As MasterDetailDataInGridview.UserControls.OrderDetails = CType(e.Row.FindControl("ucOrderDetails"), MasterDetailDataInGridview.UserControls.OrderDetails)
                If ucOrderDetails IsNot Nothing Then
                    If OrderID <> -1 And OrderID <> 0 Then
                        ucOrderDetails.BindOrderDetail(OrderID)
                    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
            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 mũi tên trỏ xuống danh sách các sản phẩm của đơn hàng sẽ xuất hiện.

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