Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

DataGrid asp:BoundColumn ArrayList Object Traversal

Posted on 2005-05-04
7
Medium Priority
?
693 Views
Last Modified: 2012-05-05
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

 
0
Comment
Question by:JerryRodgers
  • 6
7 Comments
 
LVL 23

Expert Comment

by:b1xml2
ID: 13933429
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
 
LVL 23

Expert Comment

by:b1xml2
ID: 13933433
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
 
LVL 23

Expert Comment

by:b1xml2
ID: 13933463
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:JerryRodgers
ID: 13936556
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
 
LVL 23

Accepted Solution

by:
b1xml2 earned 500 total points
ID: 13937024
<%@ 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
 
LVL 23

Expert Comment

by:b1xml2
ID: 13937387
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
 
LVL 23

Expert Comment

by:b1xml2
ID: 13937396
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

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses
Course of the Month13 days, 11 hours left to enroll

580 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question