Reputation: 1793
I am populating a DataTable using ADO.NET and binding a DataList and it works. But when I try to extract only 10 records using Linq from DataTable as shown below, my code gives an error:
var xx=dt.asEnumerable().take(10).tolist();
dglist.datasource=xx;
dglist.databind();
<asp:DataList ID="dglist" runat="server"
RepeatColumns="4" RepeatDirection="Horizontal"
RepeatLayout="Table" CellPadding="1">
<ItemTemplate>
<div>
<asp:Image runat="server" id="Image1"
src='<%# Eval("photos") %>' BorderWidth="0"
alt="" style="width:300px;height:300px;display:block;"/>
</div>
</ItemTemplate>
</asp:DataList>
My DataTable has one column called "photos". I am getting an error when I bind to a DataList. Please guide me on how I can use Linq to extract 10 records from DataTable and bind DataList with 10 records.
I have another question.
What does datatable.asEnumerable()
mean and what it does do? It seems to convert a DataTable by asEnumerable() but to what?
Upvotes: 2
Views: 915
Reputation: 139758
The DataTable
implements the IListSource
interface that is way it's supports databinding to column names (so Eval("photos")
works). But when you call AsEnumerable()
on the DataTable
it will return an IEnumerable<DataRow>
where the DataRow objects won't have the property named photos
that is why you get the exception. But you can make it work if you use an indexer in your eval with the column name:
var xx = dt.AsEnumerable().Take(10).ToList();
dglist.DataSource = xx;
dglist.DataBind();
<asp:DataList ID="dglist" runat="server"
...
<asp:Image runat="server" id="Image1"
src='<%# Eval("[photos]") %>' BorderWidth="0"
alt="" style="width:300px;height:300px;display:block;"/>
...
</asp:DataList>
Or you use the AsDataView() extension method. The OfType<object>()
is required to make the non generic collection to a generic one to support LINQ. In this case you don't need to use an indexer in your Eval
method:
var xx = dt.AsDataView().OfType<object>().Take(10).ToList();
dglist.DataSource = xx;
dglist.DataBind();
<asp:DataList ID="dglist" runat="server"
....
<asp:Image runat="server" id="Image1"
src='<%# Eval("photos") %>' BorderWidth="0"
alt="" style="width:300px;height:300px;display:block;"/>
....
</asp:DataList>
Upvotes: 1