(Nested Repeater in Asp.net) – Bài viết dưới đây sẽ hướng dẫn các bạn cách sử dụng Repeater lồng nhau và sử dụng ItemCommand.
- B1: Download CSDL Northwind tại đây và thực hiện công việc Restore Data.
- 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 NestedRepeater
{
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 NestedRepeater
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
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# Code
<%@ PageTitle="Nested Repeaters and ItemCommand in ASP.NET" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="NestedRepeater._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"runat="server">
</asp:ScriptManager>
<h3>
Nested Repeaters and ItemCommand 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:Repeater id="rptCategory" runat="server" OnItemDataBound="rptCategory_ItemDataBound">
<ItemTemplate>
<table width="100%"cellspacing="0"cellpadding="0"runat="server">
<tr>
<td>
<asp:Label CssClass="Category" id="lblCategory" runat="server" text='<%# Eval("CategoryName")%>'>
</asp:Label>
</td>
</tr>
</table>
<asp:Repeater ID="rptProduct"OnItemCommand="Detail_Command"OnItemDataBound="Detail_Bound"runat="server">
<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:LinkButton id="cmdProductName"runat="server"CommandName="Detail"CommandArgument='<%# Eval("ProductID") + "," + Eval("ProductName") + "," + Eval("UnitPrice") %>' CssClass="Title"text='<%# Eval("ProductName") %>'></asp:LinkButton>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
VB.NET Code
<%@ PageTitle="Nested Repeaters and ItemCommand in ASP.NET" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="NestedRepeater._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"runat="server">
</asp:ScriptManager>
<h3>
Nested Repeaters and ItemCommand 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:Repeater id="rptCategory" runat="server">
<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:Repeater ID="rptProduct"OnItemCommand="Detail_Command"OnItemDataBound="Detail_Bound"runat="server">
<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:LinkButton id="cmdProductName"runat="server"CommandName="Detail"CommandArgument='<%# Eval("ProductID") & "," & Eval("ProductName") & "," & Eval("UnitPrice") %>' CssClass="Title"text='<%# Eval("ProductName") %>'></asp:LinkButton>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>- B4: 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 NestedRepeater
{
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)
{
rptCategory.DataSource = objBind;
rptCategory.DataBind();
rptCategory.Visible = true;
updatePanel.Update();
}
else
{
rptCategory.Visible = false;
}
}
}
private DataTableBindData()
{
SqlDataProvider objSQL = newSqlDataProvider();
DataTable objBind = objSQL.FillTable("Select Categories.* From Categories");
return objBind;
}
private DataTableBindProduct(int CategoryID)
{
SqlDataProvider objSQL = newSqlDataProvider();
DataTable objBind = objSQL.FillTable("Select top 5 Products.* From Products Where CategoryID=" + CategoryID + "");
return objBind;
}
#endregion
#region"Repeater Methods"
protected voidrptCategory_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgse)
{
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)
{
Repeater lstDetail = (Repeater)e.Item.FindControl("rptProduct");
if (lstDetail != null)
{
lstDetail.DataSource = objBind;
lstDetail.DataBind();
}
}
}
}
public voidDetail_Command(object source, System.Web.UI.WebControls.RepeaterCommandEventArgse)
{
if (e.CommandName.ToLower() != "sort" & e.CommandName.ToLower() != "page")
{
string[] CommandArgument = e.CommandArgument.ToString().Split(',');
int ItemID = -1;
string ItemName = "";
string UnitPrice = "";
if (CommandArgument.Length > 0)
{
ItemID =Convert.ToInt32(CommandArgument[0]);
ItemName = CommandArgument[1];
UnitPrice = CommandArgument[2];
}
switch (e.CommandName.ToLower())
{
case "detail":
string sMessage = "Product Name: " + ItemName.ToString() + "\\n"+ "Price:" + UnitPrice;
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "alert", "alert('"+ sMessage + "');", true);
break;
}
}
}
public voidDetail_Bound(object sender, RepeaterItemEventArgs e)
{
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
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 voidPage_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 NestedRepeater
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
rptCategory.DataSource = objBind
rptCategory.DataBind()
rptCategory.Visible = True
updatePanel.Update()
Else
rptCategory.Visible = False
EndIf
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 SubrptCategory_ItemDataBound(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptCategory.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 AsRepeater = DirectCast(e.Item.FindControl("rptProduct"), Repeater)
If NotlstDetail Is NothingThen
lstDetail.DataSource = objBind
lstDetail.DataBind()
End If
End If
End If
End Sub
Public SubDetail_Command(ByVal source As Object, ByVal e AsSystem.Web.UI.WebControls.RepeaterCommandEventArgs)
If (e.CommandName.ToLower <> "sort" Ande.CommandName.ToLower <> "page") Then
Dim CommandArgument() As String = e.CommandArgument.ToString.Split(",")
Dim ItemID AsInteger = -1
Dim ItemName AsString = ""
Dim UnitPrice AsString = ""
If CommandArgument.Length > 0 Then
ItemID = CommandArgument(0)
ItemName = CommandArgument(1)
UnitPrice = CommandArgument(2)
End If
Select Casee.CommandName.ToLower
Case "detail"
Dim sMessage As String = "Product Name: " & ItemName.ToString() & "\n"& "Price:" & UnitPrice
ScriptManager.RegisterClientScriptBlock(Me.Page, Me.Page.GetType(), "alert", "alert('"& sMessage & "');", True)
End Select
End If
End Sub
Public SubDetail_Bound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)
Try
If (e.Item.ItemType = ListItemType.Item Ore.Item.ItemType = ListItemType.AlternatingItem) Then
Dim ProductID AsInteger = DataBinder.Eval(e.Item.DataItem, "ProductID")
Dim lnkProductImage As HyperLink = DirectCast(e.Item.FindControl("lnkProductImage"), HyperLink)
If Not lnkProductImage IsNothing 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 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
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment