중첩된 반복기 컨트롤 및 Visual C# .NET을 사용하여 계층적 데이터 표시

이 문서에서는 중첩된 반복기 컨트롤 및 Visual C# .NET을 사용하여 계층적 데이터를 표시하는 방법에 대한 정보를 제공합니다.

원래 제품 버전: Visual C#
원래 KB 번호: 306154

요약

이 문서에서는 중첩된 반복기 컨트롤을 사용하여 계층적 데이터를 표시하는 방법을 설명합니다. 이 개념을 다른 목록 바인딩된 컨트롤에 적용할 수 있습니다.

이 문서에서는 다음 Microsoft .NET Framework 클래스 라이브러리 네임스페이스를 참조합니다.

  • System.Data
  • System.Data.SqlClient

부모 테이블에 바인딩

  1. Visual Studio .NET을 시작합니다.

  2. 파일 메뉴에서 새로 만들기를 가리킨 다음 프로젝트를 클릭합니다.

  3. 프로젝트 형식에서 Visual C# 프로젝트를 클릭한 다음 템플릿에서 ASP.NET 웹 애플리케이션 클릭합니다.

  4. 위치 상자에 WebApplication#을 삭제한 다음 NestedRepeater를 입력합니다. 로컬 서버를 사용하는 경우 서버 이름을 로 둡 http://localhost니다. 경로가 http://localhost/NestedRepeater위치 상자에 나타납니다. 확인을 클릭합니다.

  5. 솔루션 탐색기 NestedRepeater 프로젝트 이름 노드를 마우스 오른쪽 단추로 클릭하고 추가를 가리킨 다음 웹 양식 추가를 클릭합니다.

  6. 웹 양식의 이름을 지정하려면 NestedRepeater를 입력하고 열기를 클릭합니다.

  7. 새 웹 양식이 만들어집니다. Visual Studio .NET의 IDE(통합 개발 환경)의 디자인 뷰에서 열립니다. 도구 상자에서 반복기 컨트롤을 선택한 다음 웹 양식 페이지로 끌어옵니다.

  8. 이 반복기 컨트롤의 ID 속성을 parentRepeater로 변경합니다.

  9. 이 웹 양식의 HTML 보기로 전환합니다. 이렇게 하려면 Designer 왼쪽 아래 모서리에 있는 HTML 탭을 클릭합니다. Repeater 컨트롤은 다음 HTML 코드를 생성합니다.

    <asp:Repeater id="parentRepeater" runat="server"></asp:Repeater>
    
  10. 태그에 Repeater 다음 코드를 추가합니다.

    <itemtemplate>
        <b>
            <%# DataBinder.Eval(Container.DataItem, "au_id") %>
        </b>
        <br>
    </itemtemplate>
    

    이렇게 하면 Repeater에 대한 HTML 코드는 다음과 같습니다.

    <asp:Repeater id="parentRepeater" runat="server">
        <itemtemplate>
            <b>
                <%# DataBinder.Eval(Container.DataItem, "au_id") %>
            </b>
            <br>
        </itemtemplate>
    </asp:Repeater>
    
  11. 솔루션 탐색기 NestedRepeater.aspx 마우스 오른쪽 단추로 클릭한 다음 코드 보기를 클릭하여 NestedRepeater.aspx.cs 코드 숨김 파일로 전환합니다.

  12. 파일 맨 위에 다음 네임스페이스 선언을 추가합니다.

    using System.Data;
    using System.Data.SqlClient;
    
  13. 이벤트에 다음 코드를 Page_Load 추가하여 Pubs 데이터베이스에 대한 연결을 만든 다음 테이블을 Repeater 컨트롤에 바인딩 Authors 합니다.

     public void Page_Load(object sender, EventArgs e)
     {
         //Create the connection and DataAdapter for the Authors table.
         SqlConnection cnn = new SqlConnection("server=(local);database=pubs; Integrated Security=SSPI");
         SqlDataAdapter cmd1 = new SqlDataAdapter("select * from authors",cnn);
    
         //Create and fill the DataSet.
         DataSet ds = new DataSet();
         cmd1.Fill(ds,"authors");
         //Insert code in step 4 of the next section here.
         //Bind the Authors table to the parent Repeater control, and call DataBind.
         parentRepeater.DataSource = ds.Tables["authors"];
         Page.DataBind();
    
         //Close the connection.
         cnn.Close();
     }
    

    참고

    사용자 환경에 맞게 데이터베이스 연결 문자열 수정해야 할 수 있습니다.

  14. 모든 파일을 저장합니다.

  15. 솔루션 탐색기 NestedRepeater.aspx 마우스 오른쪽 단추로 클릭한 다음 시작 페이지로 설정을 클릭합니다.

  16. 빌드 메뉴에서 솔루션 빌드를 클릭하여 프로젝트를 컴파일합니다.

  17. 브라우저에서 .aspx 페이지를 보고 페이지가 지금까지 작동하는지 확인합니다. 출력은 다음과 같이 표시됩니다.

    172-32-1176
    213-46-8915
    238-95-7766
    267-41-2394
    ...
    

자식 테이블에 바인딩

  1. NestedRepeater.aspx 페이지의 HTML 보기에서 다음 코드 줄을 찾습니다.

    <b>
        <%# DataBinder.Eval(Container.DataItem, "au_id") %>
    </b>
    <br>
    

    이 코드 다음에 다음 코드를 추가합니다.

    <asp:repeater id="childRepeater" runat="server">
        <itemtemplate>
            <%# DataBinder.Eval(Container.DataItem, "[\"title_id\"]")%>
            <br>
        </itemtemplate>
    </asp:repeater>
    

    이 새 코드는 부모 반복기 컨트롤의 속성에 ItemTemplate 두 번째 반복기 컨트롤을 추가합니다.

  2. DataSource 다음과 같이 자식 반복기 컨트롤의 속성을 설정합니다.

    <asp:repeater ... datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation") %>' >
    

    자식 반복기 컨트롤의 속성을 설정 DataSource 하면 두 반복기 컨트롤(부모 및 자식)에 대한 HTML 코드가 다음과 같이 표시됩니다.

    <asp:Repeater id="parentRepeater" runat="server">
        <itemtemplate>
            <b>
                <%# DataBinder.Eval(Container.DataItem, "au_id") %>
            </b>
            <br>
            <asp:repeater id="childRepeater" runat="server"
            datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation") %>' >
                <itemtemplate>
                    <%# DataBinder.Eval(Container.DataItem, "[\"title_id\"]")%><br>
                </itemtemplate>
            </asp:Repeater>
        </itemtemplate>
    </asp:Repeater>
    
  3. 페이지 맨 위에 다음 페이지 지시문을 추가합니다.

    <%@ Import Namespace="System.Data" %>
    
  4. 코드 숨김 페이지에서 이벤트에서 다음 줄을 Page_Load 바꿉 있습니다.

    //Insert code in step 4 of the next section here.
    
    //Create a second DataAdapter for the Titles table.
    SqlDataAdapter cmd2 = new SqlDataAdapter("select * from titleauthor",cnn);
    cmd2.Fill(ds,"titles");
    
    //Create the relation between the Authors and Titles tables.
    ds.Relations.Add("myrelation",
    ds.Tables["authors"].Columns["au_id"],
    ds.Tables["titles"].Columns["au_id"]);
    

    그러면 테이블이 Titles DataSet에 추가된 다음 및 테이블 간의 AuthorsTitles 관계를 추가합니다.

  5. 애플리케이션을 저장하고 컴파일합니다.

  6. 브라우저에서 페이지를 본 다음 페이지가 지금까지 작동하는지 확인합니다. 출력은 다음과 같이 표시됩니다.

    172-32-1176
    PS3333
    213-46-8915
    BU1032
    BU2075
    238-95-7766
    PC1035
    267-41-2394
    BU1111
    TC7777
    

Nestedrepeater.aspx 코드

<%@ Page language="c#" Codebehind="NestedRepeater.aspx.cs" AutoEventWireup="false" Inherits="NestedRepeater.NestedRepeater" %>
<%@ Import Namespace="System.Data" %>

<html>
    <body>
        <form runat=server>
            <!-- start parent repeater -->
            <asp:repeater id="parentRepeater" runat="server">
                <itemtemplate>
                    <b>
                        <%# DataBinder.Eval(Container.DataItem,"au_id") %>
                    </b>
                    <br>
                    <!-- start child repeater -->
                    <asp:repeater id="childRepeater" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation") %>' runat="server">
                        <itemtemplate>
                            <%# DataBinder.Eval(Container.DataItem, "[\"title_id\"]")%><br>
                        </itemtemplate>
                    </asp:repeater>
                    <!-- end child repeater -->
                </itemtemplate>
            </asp:repeater>
            <!-- end parent repeater -->
        </form>
    </body>
</html>

Nestedrepeater.aspx.cs 코드

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace NestedRepeater
{
    public class NestedRepeater : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.Repeater parentRepeater;
        public NestedRepeater()
        {
            Page.Init += new System.EventHandler(Page_Init);
        }
        public void Page_Load(object sender, EventArgs e)
        {
            //Create the connection and DataAdapter for the Authors table.
            SqlConnection cnn = new SqlConnection("server=(local);database=pubs; Integrated Security=SSPI ;");
            SqlDataAdapter cmd1 = new SqlDataAdapter("select * from authors",cnn);

            //Create and fill the DataSet.
            DataSet ds = new DataSet();
            cmd1.Fill(ds,"authors");

            //Create a second DataAdapter for the Titles table.
            SqlDataAdapter cmd2 = new SqlDataAdapter("select * from titleauthor",cnn);
            cmd2.Fill(ds,"titles");

            //Create the relation bewtween the Authors and Titles tables.
            ds.Relations.Add("myrelation",
            ds.Tables["authors"].Columns["au_id"],
            ds.Tables["titles"].Columns["au_id"]);

            //Bind the Authors table to the parent Repeater control, and call DataBind.
            parentRepeater.DataSource = ds.Tables["authors"];
            Page.DataBind();

            //Close the connection.
            cnn.Close();
        }
        private void Page_Init(object sender, EventArgs e)
        {
            InitializeComponent();
        }
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }
    }
}

추가 정보

자세한 내용은 Repeater 웹 서버 컨트롤을 참조하세요.