Bind List of object array to ListView in ASP.NET

一笑奈何 提交于 2020-01-13 04:50:08

问题


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] %>' />


来源:https://stackoverflow.com/questions/1501913/bind-list-of-object-array-to-listview-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!