-2

I'm within a Repeater and I'd like to check out which kind of object its repeating OnItemDataBound, but doing this:

public void RepeaterListato_OnItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
    Response.Write(repeaterListato.DataSource.GetType());
}

it returns the whole collection's type:

System.Collections.Generic.List`1[BrLayer.Pagina]

Not BrLayer.Pagina. Is there a way?

markzzz
  • 47,390
  • 120
  • 299
  • 507
  • 1
    Possible duplicate of [How to get the type of T from a member of a generic class or method?](https://stackoverflow.com/questions/557340/how-to-get-the-type-of-t-from-a-member-of-a-generic-class-or-method) – DerApe Aug 09 '17 at 10:51
  • 1
    @derape, A Repeater is not necessarily bound to a generic collection, so your suggested dupe is inapproriate. – Joe Aug 09 '17 at 11:01
  • 1
    Why the downvotes? Especially without a helpful comment to explain how to improve the question. – Joe Aug 09 '17 at 11:04
  • I downvoted because of the possible dupe. The collection type is of type `List<>` as we can see in your question. It doesn't matter where that list instance lives... – DerApe Aug 09 '17 at 11:06

2 Answers2

1

It absolutely is possible! Here's a working example:

class Program
{
    static List<string> MyGenericList = new List<string>();

    static void Main(string[] args)
    {
        Console.WriteLine($"My list class's type is: {MyGenericList.GetType()}, and its first generic argument is: {MyGenericList.GetType().GetGenericArguments()[0]}");
        Console.ReadLine();
    }
}

Notice the call to Type.GetType().GetGenericArguments(), that's where the magic happens. It'll return you an array of all the generic arguments of the original type.

Dan Rayson
  • 1,315
  • 1
  • 14
  • 37
1

The OnItemDataBound event handler has an argument RepeaterItemEventArgs e.

You want:

e.Item.DataItem.GetType()

Note that e.Item.DataItem will be null if e.Item.ItemType is Header, Footer, Separator or Pager; so you should check for null or check ItemType if your Repeater may have any of these elements.

Note that OnItemDataBound will be called for each item in the DataSource, and that in the general case there is no guarantee that all items will have the same Type.

Joe
  • 122,218
  • 32
  • 205
  • 338