Databind a Strongly Typed List to a ListView
- May 19th, 2010
- Posted in Ajax Postbacks
- Write comment
I tirelessly searched Google for a way to databind a strongly typed list to an Asp.Net ListView control without any good results, so now that I’ve figured this out, I thought I’d post it for the sake of others in the same boat. This is really very simple.
From what I can tell there is no Design View support for DataBinding to a ListView.
You can, however, bind the ListView from the code behind, which I believe is a lot cleaner anyway.
List<string> lSampleList = new List<string>();
lvMyListView.DataSource = lSampleList;
lvMyListView.DataBind();
<asp:ListView ID=”lvMyListView” runat=”server”>
<ItemTemplate>
<%# Container.DataItem %>
</ItemTemplate>
</asp:ListView>
Notice that there’s no need to use the Eval() method, because there’s only one value we can get at. Therefore You must use the Container.DataItem property instead. Hope this helps!