问题
I have SiteMap Datasource control on my page
<div id="content_inside">
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
<asp:TreeView ID="TreeView1" ExpandDepth="2"
</asp:TreeView>
</div>
No I am trying to bind it's tree view using the below code snippet
protected void Page_Load(object sender, EventArgs e)
{
var context = new moviescontext ();
var movies= context.movie.GetAll(ref context);
if (!IsPostBack)
{
TreeView1.DataSourceID = "SiteMapDataSource1";
TreeView1.DataSource = movies;
TreeView1.DataBind();
}
}
Where 'GetAll' is the function which fetched data from the database
public static List<movies> GetAll(this IEnumerable<movie> movie, ref moviescontext ctx)
{
var movies= ctx.movie
.Select(s => new movies
{
MovieId= s.MovieID,
MovieName = s.MovieName,
}).ToList();
return movies;
}
when I render, the following error occurred
HierarchicalDataBoundControl only accepts data sources that implement IHierarchicalDataSource or IHierarchicalEnumerable.
Any suggestion?
回答1:
You need to implement the IHierarchicalEnumerable
interface.
You can do this as follows:
public class MovieCollection : List<Movie>, IHierarchicalEnumerable
{
public IHierarchyData GetHierarchyData(object enumeratedItem)
{
return enumeratedItem as IHierarchyData;
}
public System.Collections.IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
Then add your existing movies like this:
public static List<movies> GetAll(this IEnumerable<movie> movie, ref moviescontext ctx)
{
var movies= ctx.movie
.Select(s => new movies
{
MovieId= s.MovieID,
MovieName = s.MovieName,
}).ToList();
var movieCollection = new MovieCollection();
movieCollection.AddRange(movies);
return movieCollection;
}
The TreeView is usually used to display nested data though and your current data only contains one level.
来源:https://stackoverflow.com/questions/21196356/how-to-bind-sitemap-treeview-datasource-using-c-sharp