Bind List of object array to ListView in ASP.NET

2020-07-21 09:09发布

问题:

I am breaking my head to fix an issue. I have a method that returns a List<Object[]>.

Each object[] in the List contains the following:

object[0]=Id;
object[1]=Name;

Now, I am looking for a way to bind this List to a ListView in a custom ItemTemplate which would look as follows:

<asp:Label runat="server" ID="lblId"
    Text="Here want to do an Eval/Bind for object[0]"></asp:Label>

<asp:Label runat="server" ID="lblName"
    Text="Here want to do an Eval/Bind for object[1]"></asp:Label>

Any suggestions will be deeply appreciated.

回答1:

Your datasource is not capable for standard databinding. Convert it to a name value pair, which will have a name and a value for each item that will be binded. For example Dictionary<string, string> collection is compatible for this. And then just turn your ListView to this :

<asp:Label runat="server" ID="lblId"
    Text='<%# Eval("Key") %>'></asp:Label>

<asp:Label runat="server" ID="lblName"
    Text='<%# Eval("Value") %>'></asp:Label>


回答2:

A list of object arrays is a poor choice to store items in. You should consider using a class that represents the item, or a Dictionary as @Canavar suggested. Then you would be able to use the Eval method in a cleaner fashion.

That said, it is possible to bind with your current setup, although the syntax makes my eyes bleed.

<asp:Label runat="server" ID="lblId"
    Text='<%# ((Object[])Container.DataItem)[0] %>' />
<asp:Label runat="server" ID="lblName"
    Text='<%# ((Object[])Container.DataItem)[1] %>' />