DataGrid asp:BoundColumn ArrayList Object Traversal

Hi,

I have an array list that has a list of objects in it all works well except that this object also has a property that is of a type that I would like to traverse show a few of its properties. How can I do this?

For example.

ArrayList has a collection of UserTransactions

UserTransactions has properties like:

String Prop1
Person person


Person class has;
Sring FirstName

And when I bind the column to

<asp:BoundColumn DataField="Person.FirstName" HeaderText="First Name" />

I get the following error:
Error: A field or property with the name 'Person.FirstName' was not found on the selected datasource.

I'd rather not create methods that delegate and get the property for me if I doon't have to...

Thanks,
Jerry

 
JerryRodgersAsked:
Who is Participating?
 
b1xml2Commented:
<%@ Import Namespace="..." %> //include the namespace which holds the Person and UserTransaction class

<asp:TemplateColumn>
<HeaderTemplate>Lead First Name</HeaderTemplate>
<ItemTemplate><%# ((UserTransaction)Container.DataItem).Person.FirstName%></ItemTemplate>
</asp:TemplateColumn>
0
 
b1xml2Commented:
use this:
Public Class CustomerCollection
    Inherits CollectionBase

    Protected Shared ReadOnly ObjectType As Type = GetType(Person)
    Protected Shared ReadOnly InvalidCustomerException As New ArgumentException(String.Format("Value must be of type {0}", GetType(Person)))

    Private Function IsValidType(ByVal value As Type) As Boolean
        Return value.FullName.Equals(ObjectType.FullName)
    End Function

    Protected Overrides Sub OnInsert(ByVal index As Integer, ByVal value As Object)
        If Not IsValidType(value.GetType()) Then
            Throw InvalidCustomerException
        End If
    End Sub


    Protected Overrides Sub OnRemove(ByVal index As Integer, ByVal value As Object)
        If Not IsValidType(value.GetType()) Then
            Throw InvalidCustomerException
        End If
    End Sub

    Protected Overrides Sub OnValidate(ByVal value As Object)
        If Not IsValidType(value.GetType()) Then
            Throw InvalidCustomerException
        End If
    End Sub

    Public Overridable Sub Add(ByVal value As Person)
        MyBase.List.Add(value)
    End Sub

    Public Overridable Function Insert(ByVal value As Person) As Person
        Add(value)
        Return value
    End Function

   
    Public Overridable Sub AddRange(ByVal values As Person())
        For Each value As Customer In values
            Add(value)
        Next
    End Sub

    Public Overridable Sub Remove(ByVal value As Person)
        If MyBase.List.Contains(value) Then
            MyBase.List.Remove(value)
        End If
    End Sub

    Default ReadOnly Property Items(ByVal index As Integer) As Person
        Get
            Dim value As Customer = Nothing
            If index > -1 AndAlso index < MyBase.List.Count Then
                value = DirectCast(MyBase.List(index), Customer)
            End If
            Return value
        End Get
    End Property

   
End Class


1. add persons to this collection
2. set the datasource to this collection
3. <asp:BoundColumn DataField="FirstName" HeaderText="First Name" /> would be enough
0
 
b1xml2Commented:
typos:
====
1. Anything that has the word Customer should be replaced with Person.


again the code
===========
Public Class PersonCollection
    Inherits CollectionBase

    Protected Shared ReadOnly ObjectType As Type = GetType(Person)
    Protected Shared ReadOnly InvalidPersonException As New ArgumentException(String.Format("Value must be of type {0}", GetType(Person)))

    Private Function IsValidType(ByVal value As Type) As Boolean
        Return value.FullName.Equals(ObjectType.FullName)
    End Function

    Protected Overrides Sub OnInsert(ByVal index As Integer, ByVal value As Object)
        If Not IsValidType(value.GetType()) Then
            Throw InvalidPersonException
        End If
    End Sub


    Protected Overrides Sub OnRemove(ByVal index As Integer, ByVal value As Object)
        If Not IsValidType(value.GetType()) Then
            Throw InvalidPersonException
        End If
    End Sub

    Protected Overrides Sub OnValidate(ByVal value As Object)
        If Not IsValidType(value.GetType()) Then
            Throw InvalidPersonException
        End If
    End Sub

    Public Overridable Sub Add(ByVal value As Person)
        MyBase.List.Add(value)
    End Sub

    Public Overridable Function Insert(ByVal value As Person) As Person
        Add(value)
        Return value
    End Function

   
    Public Overridable Sub AddRange(ByVal values As Person())
        For Each value As Person In values
            Add(value)
        Next
    End Sub

    Public Overridable Sub Remove(ByVal value As Person)
        If MyBase.List.Contains(value) Then
            MyBase.List.Remove(value)
        End If
    End Sub

    Default ReadOnly Property Items(ByVal index As Integer) As Person
        Get
            Dim value As Person = Nothing
            If index > -1 AndAlso index < MyBase.List.Count Then
                value = DirectCast(MyBase.List(index), Person)
            End If
            Return value
        End Get
    End Property

   
End Class



0
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

 
b1xml2Commented:
Also the references:
Imports System.Collections.

Note I have this originally in C# and if you want the code in C#, please say so.

The idea here is that if you have a collection class that inherits off collectionbase, you can just about plug that to any server control...
0
 
JerryRodgersAuthor Commented:
Hi,

Thanks but I am not sure that is exactly what I am looking for - I have a collection of UserTransactions  - those objects have 5 or so properties that I want to display (which I can easily display 4 of) However on of the properties is of type Person - not a collection of Persons but one instance that I want to travers into and read one (or more) of its properties too - and show in the grid.

code is C#

<asp:BoundColumn DataField="DateTimeOfTransaction" HeaderText="Lead First Name" />
<asp:BoundColumn DataField="TransactionMode" HeaderText="Lead First Name" />
<asp:BoundColumn DataField="TransactionErrorMessage" HeaderText="Lead First Name" />
<asp:BoundColumn DataField="Person.FirstName"  HeaderText="Lead First Name" />
<asp:BoundColumn DataField="Person.LastName"  HeaderText="Lead Last Name" />

THanks,
Jerry
0
 
b1xml2Commented:
here's the code in full
===================
using System;
using System.Collections;

namespace b1xml2.ExpertsExchange.CSharp
{
      /// <summary>
      /// Summary description for UserTransactions.
      /// </summary>
      public sealed class UserTransactionCollection : CollectionBase
      {
            private static readonly Type ObjectType = typeof(UserTransaction);
            private static readonly ArgumentException InvalidArgumentException = new ArgumentException(string.Format("Value must be of type {0}",typeof(UserTransaction)));
            
            public UserTransactionCollection() {}

            public bool IsValidType(object value)
            {
                  return value != null && value.GetType() == UserTransactionCollection.ObjectType;
            }

            protected override void OnInsert(int index, object value)
            {
                  if (! IsValidType(value))
                        throw UserTransactionCollection.InvalidArgumentException;
                  
                  base.OnInsert (index, value);
                  
            }

            protected override void OnValidate(object value)
            {
                  if (! IsValidType(value))
                        throw UserTransactionCollection.InvalidArgumentException;

                  base.OnValidate (value);
            }

            protected override void OnRemove(int index, object value)
            {
                  if (! IsValidType(value))
                        throw UserTransactionCollection.InvalidArgumentException;

                  base.OnRemove (index, value);
            }

            public void Add(UserTransaction value)
            {
                  this.List.Add(value);
            }

            public void AddRange(UserTransaction [] values)
            {
                  foreach(UserTransaction value in values)
                  {
                        Add(value);
                  }
            }

            public void Remove(UserTransaction value)
            {
                  if (this.List.Contains(value))
                  {
                        this.List.Remove(value);
                  }
            }

            public UserTransaction this [int index]
            {
                  get
                  {
                        return (UserTransaction)this.List[index];
                  }
            }





      
      }
      public sealed class UserTransaction
      {
            private Person person;
            private DateTime dateTime;
            private string mode;
            private string errorMessage;

            public UserTransaction(Person person)
            {
                  this.person = person;
            }
            
            public UserTransaction() : this(new Person())
            {

            }

            public Person Person
            {
                  get { return this.person; }
            }

            public DateTime DateTime
            {
                  get { return this.dateTime; }
                  set { this.dateTime = value; }
            }

            public string Mode
            {
                  get { return this.mode;}
                  set { this.mode = value; }
            }

            public string ErrorMessage
            {
                  get { return this.errorMessage; }
                  set { this.errorMessage = value; }
            }
            

      }

      public sealed class Person
      {
            private string firstName;
            private string lastName;

            public Person()
            {

            }
            public Person(string firstName, string lastName)
            {
                  this.firstName = firstName;
                  this.lastName = lastName;
            }

            public string FirstName
            {
                  get { return this.firstName; }
                  set { this.firstName = value; }
            }

            public string LastName
            {
                  get { return this.lastName; }
                  set { this.lastName = value; }
            }
      }


}
0
 
b1xml2Commented:
aspx
===
<%@ Page language="c#" Codebehind="WebForm6.aspx.cs" AutoEventWireup="false" Inherits="b1xml2.ExpertsExchange.CSharp.WebForm6" %>
<%@ Import Namespace="b1xml2.ExpertsExchange.CSharp"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
  <HEAD>
    <title>WebForm6</title>
<meta content="Microsoft Visual Studio .NET 7.1" name=GENERATOR>
<meta content=C# name=CODE_LANGUAGE>
<meta content=JavaScript name=vs_defaultClientScript>
<meta content=http://schemas.microsoft.com/intellisense/ie5 name=vs_targetSchema>
  </HEAD>
<body MS_POSITIONING="FlowLayout">
<form id=Form1 method=post runat="server"><asp:datagrid id=DataGrid1 runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundColumn DataField="DateTime" HeaderText="Transaction Date" DataFormatString="{0:dd-MMM-yyyy}"></asp:BoundColumn>
<asp:BoundColumn DataField="Mode" HeaderText="Transaction Mode"></asp:BoundColumn>
<asp:BoundColumn DataField="ErrorMessage" HeaderText="Error Message"></asp:BoundColumn>
<asp:TemplateColumn>
<HeaderTemplate>First Name</HeaderTemplate>
<ItemTemplate><%# ((UserTransaction)Container.DataItem).Person.FirstName %></ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<HeaderTemplate>Last Name</HeaderTemplate>
<ItemTemplate><%# ((UserTransaction)Container.DataItem).Person.LastName %></ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid></FORM>
      
  </body>
</HTML>


aspx.cs
=====
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace b1xml2.ExpertsExchange.CSharp
{
      /// <summary>
      /// Summary description for WebForm6.
      /// </summary>
      public class WebForm6 : System.Web.UI.Page
      {

            protected System.Web.UI.WebControls.DataGrid DataGrid1;
      
            private void Page_Load(object sender, System.EventArgs e)
            {
                  // Put user code to initialize the page here
                  if (! IsPostBack)
                  {
                        UserTransactionCollection collection = new UserTransactionCollection();

                        UserTransaction transaction = new UserTransaction();
                        transaction.DateTime = DateTime.Today;
                        transaction.Mode = "Insert";
                        transaction.ErrorMessage = string.Empty;
                        transaction.Person.FirstName = "John";
                        transaction.Person.LastName = "Doe";

                        collection.Add(transaction);

                        DataGrid1.DataSource = collection;
                        DataGrid1.DataBind();
                  }
            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    
                  this.Load += new System.EventHandler(this.Page_Load);

            }
            #endregion

            
      }
}
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.