News Ticker

Menu

Nested Repeater and ItemCommand in ASP.NET

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

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




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



B1Download 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 StringAs 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# Code
<%@ Page Title="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>
                                                <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: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
<%@ Page Title="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>
                                                <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: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 void BindCategories()
        {
            DataTable objBind = new DataTable();
            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 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 "Repeater Methods"

        protected void rptCategory_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs 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)
                {
                    Repeater lstDetail = (Repeater)e.Item.FindControl("rptProduct");
                    if (lstDetail != null)
                    {
                        lstDetail.DataSource = objBind;
                        lstDetail.DataBind();
                    }
                }
            }
        }

        public void Detail_Command(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
        {
            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 void Detail_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 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 NestedRepeater

    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
                    rptCategory.DataSource = objBind
                    rptCategory.DataBind()
                    rptCategory.Visible = True
                    updatePanel.Update()
                Else
                    rptCategory.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 rptCategory_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptCategory.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 Repeater = DirectCast(e.Item.FindControl("rptProduct"), Repeater)
                    If Not lstDetail Is Nothing Then
                        lstDetail.DataSource = objBind
                        lstDetail.DataBind()
                    End If
                End If
            End If
        End Sub

        Public Sub Detail_Command(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterCommandEventArgs)
            If (e.CommandName.ToLower <> "sort" And e.CommandName.ToLower <> "page") Then
                Dim CommandArgument() As String = e.CommandArgument.ToString.Split(",")
                Dim ItemID As Integer = -1
                Dim ItemName As String = ""
                Dim UnitPrice As String = ""

                If CommandArgument.Length > 0 Then
                    ItemID = CommandArgument(0)
                    ItemName = CommandArgument(1)
                    UnitPrice = CommandArgument(2)
                End If

                Select Case e.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 Sub Detail_Bound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)
            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 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



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 " Nested Repeater and ItemCommand in 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