Visualizzare i dati gerarchici usando i controlli Repeater annidati e Visual C# .NET

Questo articolo fornisce informazioni su come visualizzare dati gerarchici usando i controlli Repeater annidati e Visual C# .NET.

Versione originale del prodotto: Oggetto visivo C#
Numero KB originale: 306154

Riepilogo

Questo articolo descrive come usare i controlli Repeater annidati per visualizzare i dati gerarchici. È possibile applicare questo concetto ad altri controlli associati a elenco.

Questo articolo fa riferimento agli spazi dei nomi della libreria di classi di Microsoft .NET Framework seguenti:

  • System.Data
  • System.Data.SqlClient

Eseguire il binding alla tabella padre

  1. Avviare Visual Studio .NET.

  2. Scegliere Nuovo dal menu File, quindi fare clic su Progetto.

  3. Fare clic su Progetti Visual C# in Tipi di progetto e quindi su ASP.NET'applicazione Web in Modelli.

  4. Nella casella Percorso eliminare WebApplication# e quindi digitare NestedRepeater. Se si usa il server locale, lasciare il nome del server come http://localhost. Il http://localhost/NestedRepeater percorso viene visualizzato nella casella Percorso . Fare clic su OK.

  5. In Esplora soluzioni fare clic con il pulsante destro del mouse sul nodo NestedRepeater project name (Nome progetto NestedRepeater), scegliere Aggiungi e quindi fare clic su Aggiungi web form.

  6. Per assegnare un nome al Web Form, digitare NestedRepeater e fare clic su Apri.

  7. Viene creato il nuovo Web Form. Verrà visualizzata in Visualizzazione progettazione nell'ambiente di sviluppo integrato (IDE) di Visual Studio .NET. Nella casella degli strumenti selezionare il controllo Ripetitore e quindi trascinarlo nella pagina Web Form.

  8. Modificare la proprietà ID di questo controllo Repeater in parentRepeater.

  9. Passare alla visualizzazione HTML per questo Web Form. A tale scopo, fare clic sulla scheda HTML nell'angolo inferiore sinistro del Designer. Il controllo Repeater genera il codice HTML seguente:

    <asp:Repeater id="parentRepeater" runat="server"></asp:Repeater>
    
  10. Aggiungere il codice seguente nei Repeater tag :

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

    Dopo aver eseguito questa operazione, il codice HTML per Repeater è il seguente:

    <asp:Repeater id="parentRepeater" runat="server">
        <itemtemplate>
            <b>
                <%# DataBinder.Eval(Container.DataItem, "au_id") %>
            </b>
            <br>
        </itemtemplate>
    </asp:Repeater>
    
  11. In Esplora soluzioni fare clic con il pulsante destro del mouse su NestedRepeater.aspx e quindi scegliere Visualizza codice per passare al file code-behind NestedRepeater.aspx.cs.

  12. Aggiungere la dichiarazione dello spazio dei nomi seguente all'inizio del file:

    using System.Data;
    using System.Data.SqlClient;
    
  13. Aggiungere il codice seguente all'evento Page_Load per creare una connessione al database Pubs e quindi associare la Authors tabella al controllo Repeater:

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

    Nota

    Potrebbe essere necessario modificare il stringa di connessione del database in base alle esigenze dell'ambiente.

  14. Salvare tutti i file.

  15. In Esplora soluzioni fare clic con il pulsante destro del mouse sul NestedRepeater.aspx e quindi scegliere Imposta come pagina iniziale.

  16. Scegliere Compila soluzione dal menu Compila per compilare il progetto.

  17. Visualizzare la pagina .aspx nel browser e quindi verificare che la pagina funzioni finora. L'output dovrebbe essere visualizzato come segue:

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

Eseguire l'associazione alla tabella figlio

  1. Nella visualizzazione HTML della pagina NestedRepeater.aspx individuare la riga di codice seguente:

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

    Aggiungere il codice seguente dopo questo codice:

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

    Questo nuovo codice aggiunge un secondo controllo Repeater alla ItemTemplate proprietà del controllo Repeater padre.

  2. Impostare la DataSource proprietà per il controllo Repeater figlio come indicato di seguito:

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

    Dopo aver impostato la DataSource proprietà per il controllo Repeater figlio, il codice HTML per i due controlli Repeater (padre e figlio) viene visualizzato come segue:

    <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. Aggiungere la direttiva di pagina seguente all'inizio della pagina:

    <%@ Import Namespace="System.Data" %>
    
  4. Nella pagina code-behind sostituire la riga seguente nell'evento 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"]);
    

    In questo modo la Titles tabella viene aggiunta al DataSet e quindi vengono aggiunte le relazioni tra le Authors tabelle e Titles .

  5. Salvare e compilare l'applicazione.

  6. Visualizzare la pagina nel browser e quindi verificare che la pagina funzioni finora. L'output dovrebbe essere visualizzato come segue:

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

codice 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 codice

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

Ulteriori informazioni

Per altre informazioni, vedere Controllo server Web Repeater.