Geeks With Blogs

News
David Madden Mastering the craft one mountain at a time.

I found many websites that showed either misinformation, incorrect code, or denial of the ability to use a class as a datasource for an asp.net listview control.  It is actually very simple.

First you need to define your class.  I created private fields and public property to get and set values for those fields.  I then created a static function (since it is used often) that would return a list of the class type.

In my case, I was looking for documents that matched the page and page section so I can list them as hyerlinks.  After finding the correct folder and obtaining a list of the files, I populated the instantiated object and added it to the list of those objects.

To set and bind the datasource of the listview control I did the following:

//Set datasource and bind
ListViewWebFiles.DataSource = WebFile.GetWebFiles(_section);
ListViewWebFiles.DataBind();

My listview is in a user control to aid in dragging it to different pages. The item template is what will be used to work with the bound datasource to create the hyperlinks to the files.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebFiles.ascx.cs"
Inherits="ucWebFiles" %> <asp:ListView ID="ListViewWebFiles" runat="server">     <ItemTemplate>         <ul>             <li>                 <a href="<%# DataBinder.Eval(Container.DataItem, "FileURL") %>" 
target="_blank">                    <%# DataBinder.Eval(Container.DataItem, "DisplayName") %>                 </a>             </li>         </ul>     </ItemTemplate> </asp:ListView>

FileURL and DisplayName are the names of the publicly exposed properties of the class.  They must match.  By the way, there is an <asp:Hyperlink> that could have been used.  It would have given the same HTML output in the end.

I can now put the user control on my page and supply it with the section to do the folder lookup and output the files as hyperlinks.

<uc1:WebDocs ID="WebFiles1" runat="server" Section="SchoolPapers" />

This control was placed on Education.aspx page and my file folder virtual path is like "~/Documents/Education/SchoolPapers".

Posted on Wednesday, May 23, 2012 9:20 AM | Back to top


Comments on this post: Using a class as a datasource for asp.net listview control

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © DavidMadden | Powered by: GeeksWithBlogs.net