News Ticker

Menu

Sử dụng Datalist lồng nhau (Nested Datalist) trong Asp.net

(Nested datalist  in Asp.net) – Đối với các trang tin tức hoặc thương mại điện tử, việc sử dụng các Datalist lồng nhau thường xuyên được sử dụng. Việc sử dụng này giúp người lập trình hiển thị danh sách các chuyên mục và các bài viết trong từng chuyên mục. Bài viết dưới đây sẽ hướng dẫn các bạn cách sử dụng 2 Datalist lồng nhau, Datalist đầu sẽ hiển thị danh sách Loại và Datalist thứ 2 sẽ hiển thị danh sách sản phẩm của từng loại.

Xem những Video hay dành cho thiếu nhi - Nghe trên Youtube



Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



B1: Download CSDL Northwind tại đây và thực hiện công việc Restore Data.

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.

C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace NestedDataList
{
    public class SqlDataProvider
    {
        #region "Membres Prives"

        private string _connectionString;

        #endregion

        #region "Constructeurs"

        public SqlDataProvider()
        {
            try
            {
                _connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
            }
            catch
            {
            }
        }

        #endregion

        #region "Proprietes"

        public string ConnectionString
        {
            get { return _connectionString; }
        }

        #endregion

        #region "Functions"

        public DataTable FillTable(string sql)
        {
            try
            {
                DataTable tb = new DataTable();
                SqlDataAdapter adap = new SqlDataAdapter(sql, _connectionString);
                adap.Fill(tb);
                return tb;
            }
            catch
            {
                return null;
            }
        }

        #endregion
    }
}

VB.NET Code
Imports System.Data.SqlClient
Imports System.Data

Namespace NestedDataList

    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

#End Region

    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: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
C#
<%@ Page Title="Nested DataList in ASP.NET" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="NestedDataList._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <h3>
        Nested DataList in ASP.NET
    </h3>
    <br />
    <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table cellspacing="0" cellpadding="0" width="100%" border="0">
                <tr>
                    <td>
                        <asp:datalist id="lstCategory" runat="server" cellspacing="0" cellpadding="0" Width="100%" OnItemDataBound="lstCategory_ItemDataBound">
                            <ItemTemplate>
                                   <table width="100%" cellspacing="0" cellpadding="0" id="tblTop" runat="server">
                                             <tr>
                                        <td>
                                                          <asp:Label CssClass="Category" id="lblCategory" runat="server" text='<%#  Eval("CategoryName")%>'>
                                                          </asp:Label>
                                                   </td>
                                             </tr>
                                      </table>
                                <asp:DataList ID="lstProduct" OnItemDataBound="Detail_Bound" runat="server" CellPadding="0" CellSpacing="0" Width="100%" RepeatDirection="Horizontal" RepeatColumns="5">
                                    <ItemTemplate>
                                        <table align="left" style="border: 1px solid #cccccc; margin-top:5px; margin-bottom:5px;margin-right:5px;" width="170px" height="170px">
                                            <tr>
                                                <td align="center">
                                                    <asp:HyperLink id="lnkProductImage" runat="server" CssClass="Image">
                                                        <asp:Image id="imgProductImage" runat="server" ImageAlign="Middle" Height="120px" Width="120px" hspace="0" vspace="0"></asp:Image>
                                                    </asp:HyperLink>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td align="center" style="padding-bottom:5px;">
                                                    <asp:HyperLink ID="lnkProductName" CssClass="Title" runat="server">
                                                    </asp:HyperLink>
                                                </td>
                                            </tr>
                                        </table>
                                    </ItemTemplate>
                                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Top" />
                                </asp:DataList>
                               </ItemTemplate>
                        </asp:datalist>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

VB.Net Code
<%@ Page Title="Nested DataList in ASP.NET" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="NestedDataList._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <h3>
        Nested DataList in ASP.NET
    </h3>
    <br />
    <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table cellspacing="0" cellpadding="0" width="100%" border="0">
                <tr>
                    <td>
                        <asp:datalist id="lstCategory" runat="server" cellspacing="0" cellpadding="0" Width="100%">
                            <ItemTemplate>
                                   <table width="100%" cellspacing="0" cellpadding="0" id="tblTop" runat="server">
                                             <tr>
                                        <td>
                                                          <asp:Label CssClass="Category" id="lblCategory" runat="server" text='<%#  Eval("CategoryName")%>'>
                                                          </asp:Label>
                                                   </td>
                                             </tr>
                                      </table>
                                <asp:DataList ID="lstProduct" OnItemDataBound="Detail_Bound" runat="server" CellPadding="0" CellSpacing="0" Width="100%" RepeatDirection="Horizontal" RepeatColumns="5">
                                    <ItemTemplate>
                                        <table align="left" style="border: 1px solid #cccccc; margin-top:5px; margin-bottom:5px;margin-right:5px;" width="170px" height="170px">
                                            <tr>
                                                <td align="center">
                                                    <asp:HyperLink id="lnkProductImage" runat="server" CssClass="Image">
                                                        <asp:Image id="imgProductImage" runat="server" ImageAlign="Middle" Height="120px" Width="120px" hspace="0" vspace="0"></asp:Image>
                                                    </asp:HyperLink>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td align="center" style="padding-bottom:5px;">
                                                    <asp:HyperLink ID="lnkProductName" CssClass="Title" runat="server">
                                                    </asp:HyperLink>
                                                </td>
                                            </tr>
                                        </table>
                                    </ItemTemplate>
                                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Top" />
                                </asp:DataList>
                               </ItemTemplate>
                        </asp:datalist>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

B4: Viết Code cho file Default.aspx

C#
//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 NestedDataList
{
    public partial class _Default : System.Web.UI.Page
    {

        #region "Bind Data"

        private void BindCategories()
        {
            DataTable objBind = new DataTable();
            objBind = BindData();

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

        private DataTable BindData()
        {
            SqlDataProvider objSQL = new SqlDataProvider();
            DataTable objBind = objSQL.FillTable("Select Categories.* From Categories");
            return objBind;
        }

        private DataTable BindProduct(int CategoryID)
        {
            SqlDataProvider objSQL = new SqlDataProvider();
            DataTable objBind = objSQL.FillTable("Select top 5 Products.* From Products Where CategoryID=" + CategoryID + "");
            return objBind;
        }

        #endregion

        #region "Datalist  Methods"

        protected void lstCategory_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
            {
                int CategoryID = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "CategoryID"));
                DataTable objBind = new DataTable();

                objBind = BindProduct(CategoryID);
                if (objBind.Rows.Count != 0)
                {
                    DataList lstDetail = (DataList)e.Item.FindControl("lstProduct");
                    if (lstDetail != null)
                    {
                        lstDetail.DataSource = objBind;
                        lstDetail.DataBind();
                    }
                }
            }
        }

        public void Detail_Bound(object sender, DataListItemEventArgs e)
        {
            {
                if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    int ProductID = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "ProductID"));
                    string ProductName = DataBinder.Eval(e.Item.DataItem, "ProductName").ToString();

                    HyperLink lnkProductName = (HyperLink)e.Item.FindControl("lnkProductName");
                    if (lnkProductName != null)
                    {
                        lnkProductName.Text = ProductName;
                        lnkProductName.NavigateUrl = "Default.aspx";
                    }

                    HyperLink lnkProductImage = (HyperLink)e.Item.FindControl("lnkProductImage");
                    if (lnkProductImage != null)
                    {
                        Image imgArticleImage = (Image)lnkProductImage.FindControl("imgProductImage");
                        if (imgArticleImage != null)
                        {
                            imgArticleImage.ImageUrl = Page.ResolveUrl("Images/no_image.jpg");
                            imgArticleImage.ImageAlign = ImageAlign.AbsMiddle;
                        }
                    }
                }
            }
        }

        #endregion

        #region "Event Handles"

        protected void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    BindCategories();
                }
            }
            catch
            {
            }
        }

        #endregion
    }
}

VB.NET Code

'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials

Namespace NestedDataList

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Bind Data"

        Private Sub BindCategories()
            Dim objBind As New DataTable
            objBind = BindData()

            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then
                    lstCategory.DataSource = objBind
                    lstCategory.DataBind()
                    lstCategory.Visible = True
                    updatePanel.Update()
                Else
                    lstCategory.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 Categories.* From Categories")
            Return objBind
        End Function

        Private Function BindProduct(ByVal CategoryID As Integer) As DataTable
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable("Select top 5 Products.* From Products Where CategoryID=" & CategoryID & "")
            Return objBind
        End Function

#End Region

#Region "Datalist Methods"

        Private Sub lstCategory_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles lstCategory.ItemDataBound
            If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
                Dim CategoryID As Integer = DataBinder.Eval(e.Item.DataItem, "CategoryID")
                Dim objBind As New DataTable

                objBind = BindProduct(CategoryID)
                If objBind.Rows.Count <> 0 Then
                    Dim lstDetail As DataList = DirectCast(e.Item.FindControl("lstProduct"), DataList)
                    If Not lstDetail Is Nothing Then
                        lstDetail.DataSource = objBind
                        lstDetail.DataBind()
                    End If
                End If
            End If
        End Sub

        Public Sub Detail_Bound(ByVal sender As Object, ByVal e As DataListItemEventArgs)
            Try
                If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
                    Dim ProductID As Integer = DataBinder.Eval(e.Item.DataItem, "ProductID")
                    Dim ProductName As String = DataBinder.Eval(e.Item.DataItem, "ProductName")

                    Dim lnkProductName As HyperLink = DirectCast(e.Item.FindControl("lnkProductName"), HyperLink)
                    If Not lnkProductName Is Nothing Then
                        lnkProductName.Text = ProductName
                        lnkProductName.NavigateUrl = "Default.aspx"
                    End If

                    Dim lnkProductImage As HyperLink = DirectCast(e.Item.FindControl("lnkProductImage"), HyperLink)
                    If Not lnkProductImage Is Nothing Then
                        Dim imgArticleImage As Image = DirectCast(lnkProductImage.FindControl("imgProductImage"), Image)
                        If Not imgArticleImage Is Nothing Then
                            imgArticleImage.ImageUrl = Page.ResolveUrl("Images/no_image.jpg")
                            imgArticleImage.ImageAlign = ImageAlign.AbsMiddle
                        End If
                    End If
                End If
            Catch exception As Exception

            End Try
        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
                    BindCategories()
                End If
            Catch ex As Exception

            End Try
        End Sub

#End Region

    End Class

End Namespace

Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET




Bây giờ chạy Project chương trình sẽ hiển thị danh sách các Category và ứng với mỗi Category là danh sách các Product nằm trong nó.


Chúc các bạn thành công!

Quang Bình

Share This:

Post Tags:

Mỗi bài viết đều là công sức và thời gian của tác giả ví vậy tác giả chỉ có một mong muốn duy nhất nếu ai đó có Copy thì xin hãy ghi rõ nguồn và thông tin tác giả ở cuối mỗi bài viết.
Xin cảm ơn!

No Comment to " Sử dụng Datalist lồng nhau (Nested Datalist) trong Asp.net "

  • To add an Emoticons Show Icons
  • To add code Use [pre]code here[/pre]
  • To add an Image Use [img]IMAGE-URL-HERE[/img]
  • To add Youtube video just paste a video link like http://www.youtube.com/watch?v=0x_gnfpL3RM