Search code examples
c#asp.netdynamic-dataasp.net-dynamic-datametamodel

DynamicData - How can I show the child count in the Children.ascx.cs FieldTemplate?


MS DynamicData's Children.ascx.cs file has a Page_Load method that returns a hyperlink which says "View Children". I want to append the number of children to the end of the hyperlink text. Below is my attempt. How can I make the hyperlink say "View Children - # entries" ?

protected void Page_Load(object sender, EventArgs e)
{
    HyperLink1.Text = "View " + ChildrenColumn.ChildTable.DisplayName;

    //The following code gives the total entries.
    //How do I get the number of children only?
    //int entries = 0;
    //foreach (var entry in ChildrenColumn.ChildTable.GetQuery()) { entries++; }
    //string entryText = (entries == 1) ? "entry" : "entries";
    //HyperLink1.Text= HyperLink1.Text + " " + entries + " " + entryText;
}

Solution

  • Actually it is not that hard. You can add the following Method to your Children.ascx.cs file:

        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);
    
            object entity;
            ICustomTypeDescriptor rowDescriptor = Row as ICustomTypeDescriptor;
            if (rowDescriptor != null)
            {
                // Get the real entity from the wrapper
                entity = rowDescriptor.GetPropertyOwner(null);
            }
            else
            {
                entity = Row;
            }
    
            // Get the collection and make sure it's loaded
            RelatedEnd entityCollection = Column.EntityTypeProperty.GetValue(entity, null) as RelatedEnd;
            if (entityCollection == null)
            {
                throw new InvalidOperationException(String.Format("The Children template does not support the collection type of the '{0}' column on the '{1}' table.", Column.Name, Table.Name));
            }
            if (!entityCollection.IsLoaded)
            {
                entityCollection.Load();
            }
    
            int count = 0;
            var enumerator = entityCollection.GetEnumerator();
            while (enumerator.MoveNext())
                count++;
    
            HyperLink1.Text += " (" + count + ")";
        }