How to Bind SiteMap Treeview datasource using c#

妖精的绣舞 提交于 2019-12-24 17:24:11

问题


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

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