(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.
- 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 stringConnectionString
{
get { return_connectionString; }
}
#endregion
#region"Functions"
public DataTableFillTable(string sql)
{
try
{
DataTable tb = new DataTable();
SqlDataAdapter adap = new SqlDataAdapter(sql, _connectionString);
adap.Fill(tb);
return tb;
}
catch
{
return null;
}
}
#endregion
}
}
Imports System.Data.SqlClient
Imports System.Data
Namespace NestedDataList
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
#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#
<%@ PageTitle="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>
<tdalign="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
<%@ PageTitle="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>
<tdalign="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>
<tdalign="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 voidBindCategories()
{
DataTable objBind = newDataTable();
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 DataTableBindData()
{
SqlDataProvider objSQL = newSqlDataProvider();
DataTable objBind = objSQL.FillTable("Select Categories.* From Categories");
return objBind;
}
private DataTableBindProduct(int CategoryID)
{
SqlDataProviderobjSQL = new SqlDataProvider();
DataTable objBind = objSQL.FillTable("Select top 5 Products.* From Products Where CategoryID=" + CategoryID + "");
return objBind;
}
#endregion
#region"Datalist Methods"
protected voidlstCategory_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgse)
{
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 voidDetail_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(objectsender, 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 SubBindCategories()
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 FunctionBindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Select Categories.* From Categories")
Return objBind
End Function
Private FunctionBindProduct(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 SublstCategory_ItemDataBound(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.DataListItemEventArgs) Handles lstCategory.ItemDataBound
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim CategoryID AsInteger = DataBinder.Eval(e.Item.DataItem, "CategoryID")
Dim objBind AsNew DataTable
objBind = BindProduct(CategoryID)
If objBind.Rows.Count <> 0 Then
Dim lstDetail AsDataList = DirectCast(e.Item.FindControl("lstProduct"), DataList)
If NotlstDetail Is NothingThen
lstDetail.DataSource = objBind
lstDetail.DataBind()
End If
End If
End If
End Sub
Public SubDetail_Bound(ByVal sender As Object, ByVal e As DataListItemEventArgs)
Try
If (e.Item.ItemType = ListItemType.Item Ore.Item.ItemType = ListItemType.AlternatingItem) Then
Dim ProductID AsInteger = DataBinder.Eval(e.Item.DataItem, "ProductID")
DimProductName As String= DataBinder.Eval(e.Item.DataItem, "ProductName")
Dim lnkProductName As HyperLink = DirectCast(e.Item.FindControl("lnkProductName"), HyperLink)
If NotlnkProductName Is NothingThen
lnkProductName.Text = ProductName
lnkProductName.NavigateUrl = "Default.aspx"
End If
Dim lnkProductImage As HyperLink = DirectCast(e.Item.FindControl("lnkProductImage"), HyperLink)
If NotlnkProductImage Is NothingThen
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 SubPage_Load(ByVal sender AsObject, 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
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
0 comments Blogger 0 Facebook
Post a Comment