Las listas 7.7 y 7.8 dan un código completo para un ejemplo de página de selección TreeView, como muestra las figuras 1 y 2. Estas figuras también ilustran sus nodos productos usando check boxes. El usuario puede también checkear uno o mas de estos boxes, y entonces clickear el boton comprar.
Listing 7.7 TreeEventHandling.aspx
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class TreeEventHandling : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Fill tree with data
FillTree();
// Let's begin with all the nodes collapsed as well
treeMain.CollapseAll();
}
}
///
/// Helper method to fill tree with data
///
private void FillTree()
{
// Get all the groups and iterate through them
string[] groups = ProductCatalog.GetGroups();
foreach (string grp in groups)
{
// Create the node for the group
TreeNode groupNode = new TreeNode(grp);
// For each group get their subheadings and process them
string[] subheadings =
ProductCatalog.GetSubHeadingsByGroup(grp);
foreach (string sub in subheadings)
{
// Create the node for the subheading
TreeNode subheadingNode = new TreeNode(sub);
// For each subheading, get their products
// and process them
Product[] products =
ProductCatalog.GetProductObjectsBySubHeading(sub);
foreach (Product prod in products)
{
// Create new product tree node
TreeNode productNode = new TreeNode(prod.Name);
// Set the node's value to the product id
productNode.Value = prod.Id.ToString();
// Add product node to its parent
subheadingNode.ChildNodes.Add(productNode);
}
// Add subheading node to its parent
groupNode.ChildNodes.Add(subheadingNode);
}
// Add group node to its parent
treeMain.Nodes.Add(groupNode);
}
}
///
/// Handles the tree node selection event
///
protected void SelectProduct(object sender, EventArgs e)
{
// Get the tree node that was selected
TreeNode node = treeMain.SelectedNode;
// Only process selection if a leaf node selected
if (node.ChildNodes.Count == 0)
{
// Retrieve the product id that we placed in the node
int id = Convert.ToInt32(node.Value);
// From that product id get the product
Product prod = ProductCatalog.GetProductById(id);
// If this is a valid product, display details
if (prod != null)
{
txtId.Text = prod.Id.ToString();
txtIsbn.Text = prod.Isbn;
txtName.Text = prod.Name;
txtPrice.Text = String.Format("{0:c}", prod.Price);
}
}
}
///
/// Handles the purchase button click event
///
protected void btnPurchase_Click(object sender, EventArgs e)
{
// Handle the fact there may be no checked products
if (treeMain.CheckedNodes.Count <= 0)
No hay comentarios:
Publicar un comentario