Exibir dados hierárquicos usando controles repetidos aninhados e Visual C# .NET

Este artigo fornece informações sobre como exibir dados hierárquicos usando controles repetidos aninhados e Visual C# .NET.

Versão original do produto: Visual C#
Número de KB original: 306154

Resumo

Este artigo descreve como usar controles repetidos aninhados para exibir dados hierárquicos. Você pode aplicar esse conceito a outros controles vinculados à lista.

Este artigo refere-se aos seguintes namespaces da Biblioteca de Classes da Microsoft .NET Framework:

  • System.Data
  • System.Data.SqlClient

Associar-se à tabela pai

  1. Inicie o Visual Studio .NET.

  2. No menu arquivo, aponte para novo e, em seguida, clique em Project.

  3. Clique em Projetos do Visual C# em Tipos de Projeto e clique em ASP.NET Aplicativo Web em Modelos.

  4. Na caixa Localização , exclua o WebApplication#e digite NestedRepeater. Se você usar o servidor local, deixe o nome do servidor como http://localhost. O http://localhost/NestedRepeater caminho é exibido na caixa Localização . Clique em OK.

  5. Em Gerenciador de Soluções, clique com o botão direito do mouse no nó Nome do projeto NestedRepeater, aponte para Adicionar e clique em Adicionar Formulário Web.

  6. Para nomear o Formulário Web, digite AninhadoRepeater e clique em Abrir.

  7. O novo Formulário Web é criado. Ele é aberto no Design View no IDE (Ambiente de Desenvolvimento Integrado) do Visual Studio .NET. Na caixa de ferramentas, selecione o controle Repetidor e arraste-o para a página Formulário da Web.

  8. Altere a propriedade ID desse controle Repeater para parentRepeater.

  9. Alterne para a exibição HTML para este Formulário Web. Para fazer isso, clique na guia HTML no canto inferior esquerdo do Designer. O controle Repetidor gera o seguinte código HTML:

    <asp:Repeater id="parentRepeater" runat="server"></asp:Repeater>
    
  10. Adicione o seguinte código nas Repeater marcas:

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

    Depois de fazer isso, o código HTML do Repetidor é o seguinte:

    <asp:Repeater id="parentRepeater" runat="server">
        <itemtemplate>
            <b>
                <%# DataBinder.Eval(Container.DataItem, "au_id") %>
            </b>
            <br>
        </itemtemplate>
    </asp:Repeater>
    
  11. Em Gerenciador de Soluções, clique com o botão direito do mouse em NestedRepeater.aspx e clique em Exibir Código para alternar para o arquivo NestedRepeater.aspx.cs code-behind.

  12. Adicione a seguinte declaração de namespace à parte superior do arquivo:

    using System.Data;
    using System.Data.SqlClient;
    
  13. Adicione o seguinte código ao Page_Load evento para criar uma conexão com o banco de dados Pubs e, em seguida, associar a Authors tabela ao controle Repetidor:

     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();
     }
    

    Observação

    Talvez seja necessário modificar o banco de dados cadeia de conexão conforme apropriado para seu ambiente.

  14. Salve todos os arquivos.

  15. Em Gerenciador de Soluções, clique com o botão direito do mouse no NestedRepeater.aspx e clique em Definir Como Página inicial.

  16. No menu Compilar , clique em Criar solução para compilar o projeto.

  17. Exiba a página .aspx no navegador e verifique se a página funciona até agora. A saída deve aparecer da seguinte maneira:

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

Associar à tabela filho

  1. Na exibição HTML da página NestedRepeater.aspx , localize a seguinte linha de código:

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

    Adicione o seguinte código após este código:

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

    Este novo código adiciona um segundo controle Repetidor à ItemTemplate propriedade do controle repositório pai.

  2. Defina a DataSource propriedade para o controle repetidor filho da seguinte maneira:

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

    Depois de definir a DataSource propriedade para o controle repetidor filho, o código HTML para os dois controles repeater (pai e filho) será exibido da seguinte maneira:

    <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. Adicione a seguinte diretiva de página à parte superior da página:

    <%@ Import Namespace="System.Data" %>
    
  4. Na página code-behind, substitua a seguinte linha no Page_Load evento:

    //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"]);
    

    Isso adiciona a Titles tabela ao DataSet e adiciona as relações entre as tabelas eTitles.Authors

  5. Salve e compile o aplicativo.

  6. Exiba a página no navegador e verifique se a página funciona até agora. A saída deve aparecer da seguinte maneira:

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

Nestedrepeater.aspx código

<%@ 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 código

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);
        }
    }
}

Mais informações

Para obter mais informações, consulte Controle de Servidor Web Repetidor.