views:

212

answers:

2

Lets say I have a class that stores user information complete with getters and setters, and it is populated with data from an XML file. How would I iterate over all of the instances of that class like you would do with java beans and tag libraries?

A: 

This assumes you can acquire all instances of your class and add them to a Generic List.

List<YourClass> myObjects = SomeMagicMethodThatGetsAllInstancesOfThatClassAndAddsThemtoTheCollection();
foreach (YourClass instance in myObjects)
{
Response.Write(instance.PropertyName.ToString();
}

If you don't want to specify each property name you could use Reflection, (see PropertyInfo) and do it that way. Again, not sure if this is what your intent was.

RandomNoob
Will this work in the aspx page?
Ethan Gunderson
yes Response.Write will just write to the current http output. It *will* work on an aspx page, if you want, create a List of integers and write them out on page load as shown above.
RandomNoob
+1  A: 

For outputting formatted HTML, you have a few choices. What I would probably do is make a property on the code-behind that accesses the collection of objects you want to iterate over. Then, I'd write the logic for iterating and formatting them on the .aspx page itself. For example, the .aspx page:

[snip]
<body>
    <form id="form1" runat="server">
        <% Somethings.ForEach(s => { %>
            <h1><%=s.Name %></h1>
            <h2><%=s.Id %></h2>
        <% }); %>
    </form>
</body>
</html>

And then the code-behind:

[snip]
public partial class _Default : System.Web.UI.Page
    {
        protected List<Something> Somethings { get; private set; }
        protected void Page_Load(object sender, EventArgs e)
        {
            Somethings = GetSomethings(); // Or whatever populates the collection

        }
[snip]

You could also look at using a repeater control and set the DataSource to your collection. It's pretty much the same idea as the code above, but I think this way is clearer (in my opinion).

muloh