TreeView.PopulateNodesFromClient Propiedad

Definición

Obtiene o establece un valor que indica si los datos de nodo se rellenan a demanda del cliente.

C#
public bool PopulateNodesFromClient { get; set; }

Valor de propiedad

true para rellenar los datos del nodo de árbol a demanda del cliente; de lo contrario, false. De manera predeterminada, es true.

Ejemplos

En el ejemplo de código siguiente se muestra cómo usar la propiedad para habilitar el PopulateNodesFromClient rellenado del lado cliente de los nodos del TreeView control . Tenga en cuenta que cuando el rellenado de nodos del lado cliente está habilitado, los nodos se rellenan dinámicamente en el cliente, sin necesidad de volver a publicar en el servidor.

ASP.NET (C#)

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  void PopulateNode(Object sender, TreeNodeEventArgs e)
  {

    // Call the appropriate method to populate a node at a particular level.
    switch(e.Node.Depth)
    {
      case 0:
        // Populate the first-level nodes.
        PopulateCategories(e.Node);
        break;
      case 1:
        // Populate the second-level nodes.
        PopulateProducts(e.Node);
        break;
      default:
        // Do nothing.
        break;
    }
    
  }

  void PopulateCategories(TreeNode node)
  {
    
    // Query for the product categories. These are the values
    // for the second-level nodes.
    DataSet ResultSet = RunQuery("Select CategoryID, CategoryName From Categories");

    // Create the second-level nodes.
    if(ResultSet.Tables.Count > 0)
    {
    
      // Iterate through and create a new node for each row in the query results.
      // Notice that the query results are stored in the table of the DataSet.
      foreach (DataRow row in ResultSet.Tables[0].Rows)
      {
        
        // Create the new node. Notice that the CategoryId is stored in the Value property 
        // of the node. This will make querying for items in a specific category easier when
        // the third-level nodes are created. 
        TreeNode newNode = new TreeNode();
        newNode.Text = row["CategoryName"].ToString(); 
        newNode.Value = row["CategoryID"].ToString();        

        // Set the PopulateOnDemand property to true so that the child nodes can be 
        // dynamically populated.
        newNode.PopulateOnDemand = true;
        
        // Set additional properties for the node.
        newNode.SelectAction = TreeNodeSelectAction.Expand;
        
        // Add the new node to the ChildNodes collection of the parent node.
        node.ChildNodes.Add(newNode);
        
      }
      
    }
    
  }

  void PopulateProducts(TreeNode node)
  {

    // Query for the products of the current category. These are the values
    // for the third-level nodes.
    DataSet ResultSet = RunQuery("Select ProductName From Products Where CategoryID=" + node.Value);

    // Create the third-level nodes.
    if(ResultSet.Tables.Count > 0)
    {
    
      // Iterate through and create a new node for each row in the query results.
      // Notice that the query results are stored in the table of the DataSet.
      foreach (DataRow row in ResultSet.Tables[0].Rows)
      {
      
        // Create the new node.
        TreeNode NewNode = new TreeNode(row["ProductName"].ToString());
        
        // Set the PopulateOnDemand property to false, because these are leaf nodes and
        // do not need to be populated.
        NewNode.PopulateOnDemand = false;
        
        // Set additional properties for the node.
        NewNode.SelectAction = TreeNodeSelectAction.None;
        
        // Add the new node to the ChildNodes collection of the parent node.
        node.ChildNodes.Add(NewNode);
        
      }
      
    }

  }

  DataSet RunQuery(String QueryString)
  {

    // Declare the connection string. This example uses Microsoft SQL Server 
    // and connects to the Northwind sample database.
    String ConnectionString = "server=localhost;database=NorthWind;Integrated Security=SSPI"; 

    SqlConnection DBConnection = new SqlConnection(ConnectionString);
    SqlDataAdapter DBAdapter;
    DataSet ResultsDataSet = new DataSet();

    try
    {

      // Run the query and create a DataSet.
      DBAdapter = new SqlDataAdapter(QueryString, DBConnection);
      DBAdapter.Fill(ResultsDataSet);

      // Close the database connection.
      DBConnection.Close();

    }
    catch(Exception ex)
    {

      // Close the database connection if it is still open.
      if(DBConnection.State == ConnectionState.Open)
      {
        DBConnection.Close();
      }
      
      Message.Text = "Unable to connect to the database.";

    }

    return ResultsDataSet;

  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>TreeView PopulateNodesFromClient Example</title>
</head>
<body>
    <form id="form1" runat="server">
    
      <h3>TreeView PopulateNodesFromClient Example</h3>
    
      <asp:TreeView id="LinksTreeView"
        Font-Names= "Arial"
        ForeColor="Blue"
        EnableClientScript="true"
        PopulateNodesFromClient="true"  
        OnTreeNodePopulate="PopulateNode"
        runat="server">
         
        <Nodes>
        
          <asp:TreeNode Text="Inventory" 
            SelectAction="Expand"  
            PopulateOnDemand="true"/>
        
        </Nodes>
        
      </asp:TreeView>
      
      <br /><br />
      
      <asp:Label id="Message" runat="server"/>

    </form>
  </body>
</html>

Comentarios

A veces, no resulta práctico predefinir estáticamente la estructura de árbol debido al tamaño de los datos o al contenido personalizado que depende de la entrada del usuario. Por este motivo, el control admite el TreeView rellenado dinámico de nodos. Cuando la PopulateOnDemand propiedad de un nodo se establece trueen , ese nodo se rellena en tiempo de ejecución cuando se expande el nodo.

Además de rellenar los nodos a petición, es posible rellenar los nodos directamente en un explorador cliente compatible. Cuando la PopulateNodesFromClient propiedad se establece trueen , se llama a un servicio desde el cliente para rellenar los nodos de árbol, lo que elimina la necesidad de volver a publicar en el servidor. De lo contrario, el TreeView control vuelve a exponer al servidor para rellenar los nodos.

Nota

La EnableClientScript propiedad también debe establecerse true en para que la PopulateNodesFromClient propiedad se establezca trueen .

Para rellenar un nodo en el cliente, establezca primero la PopulateNodesFromClient propiedad true en y, a continuación, establezca la PopulateOnDemand propiedad del nodo en true. A continuación, defina un método de control de eventos para el TreeNodePopulate evento que rellena mediante programación el nodo. Un método típico de control de eventos recupera datos de nodo de un origen de datos, coloca los datos en una estructura de nodo y, a continuación, agrega la estructura del nodo a la ChildNodes colección del nodo que se está rellenando. Para crear una estructura de nodo, agregue TreeNode objetos a la ChildNodes colección de un nodo primario.

Nota

Cuando la PopulateOnDemand propiedad de un nodo se establece trueen , el nodo debe rellenarse dinámicamente. No se puede anidar mediante declaración otro nodo debajo de él; De lo contrario, se producirá un error en la página.

Nota

La característica de rellenado de nodos del lado cliente se admite en exploradores que admiten scripts de devolución de llamada. Para comprobar si un explorador admite el acceso a scripts de devolución de llamada, use la SupportsCallback propiedad de la HttpBrowserCapabilities clase . Puede acceder a la instancia de la HttpBrowserCapabilities clase para la solicitud actual a través de la Browser propiedad de la HttpRequest clase .

El valor de esta propiedad se almacena en estado de vista.

Se aplica a

Produto Versións
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

Consulte también