2012-01-20 2 views
0

У меня есть treeview на моей странице asp.net. Я хочу, чтобы мой навигации, как показано на приведенном выше рисунке прилагается .. Панель навигации в C# asp.net

, когда я попробовал это, я получаю ошибку, которая говорит:

HierarchicalDataBoundControl only accepts data sources that implement IHierarchicalDataSource or IHierarchicalEnumerable.

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!Page.IsPostBack) 
    { 
     SqlConnection cn = new SqlConnection(@"Data Source=ABID-PC\SqlExpress;Initial Catalog=SamleNavigation;Integrated Security=True"); 
     SqlCommand cmd = new SqlCommand("Select cat_Name from _NavParent", cn); 
     SqlDataAdapter da = new SqlDataAdapter(cmd); 
     DataTable dt = new DataTable(); 
     da.Fill(dt); 
     TreeViewSample.DataSource = dt; 
     TreeViewSample.DataBind(); 


    } 
} 

любая помощь будет оценена.

С уважением, Abid.

+0

Это означает, что данные, которые вы привязываете к элементу управления TreeView, должны быть иерархическими, должны содержать родительский и дочерний узлы. Например, это может быть 'XmlDataSource'. – Samich

+0

Во многих случаях можно сказать, что «картина стоит тысячи слов». Но в этом случае, однако, вам больше не нужно показывать нам соответствующие фрагменты вашего кода ... – Nailuj

ответ

0

Возможное решение. Что он задает, это тип данных, который удобен для древовидной структуры.

Прежде всего, вы должны создать свой Category класс

// Your primary class 
public class Category { 
    public Int32 CategoryId { get; set; } 
    public Int32? ParentCategoryId { get; set; } 
    public String CategoryName { get; set; } 

    // List of children if any. 
    // In this example if your category doesn't have any children 
    // it is supposed to be null 
    public List<Category> Children { get; set; } 
    // The parent category. If this is your topmost category 
    // this property is deemed to be null. 
    public Category Parent { get; set; } 

    public override String ToString() { 
     return this.CategoryName; 
    } 
} 

Он имеет ссылку на родителя и список детей. Если категория самая верхняя, Parent - null. Если у него нет детей, он также может быть нулевым.

Тогда вам понадобятся указанные обертки. Вот они

// your primary tree 
public class CategoryTree : IHierarchicalEnumerable { 
    // Field to keep the collection data 
    private IEnumerable<Category> Categories; 
    // Empty constructor 
    public CategoryTree() { 
     //Init an empty list to avoid NullReferenceException 
     Categories = new List<Category>(); 
    } 
    // Primary constructor of our interest 
    public CategoryTree(IEnumerable<Category> categories) { 
     // Assign the collection data to the internal list 
     Categories = categories; 
    } 
    public IHierarchyData GetHierarchyData(object enumeratedItem) { 
     //cast the object 
     var cat = enumeratedItem as Category; 
     //create a new hierarchy item 
     return new CategoryHierarchyItem(cat); 
    } 

    public System.Collections.IEnumerator GetEnumerator() { 
     //IEnumerable support for foreach loop 
     return Categories.GetEnumerator(); 
    } 
} 

и

// Container that the TreeView control needs 
public class CategoryHierarchyItem : IHierarchyData { 
    // Internal field to store your data 
    private Category _Item; 

    // the constructor used to instantiate the class 
    public CategoryHierarchyItem(Category input) { 
     this._Item = input; 
    } 

    // returns another tree with children if any 
    public IHierarchicalEnumerable GetChildren() { 
     if (_Item.Children != null) 
      return new CategoryTree(_Item.Children); 
     return new CategoryTree(); 
    } 

    // The boolean value indicating weather this is the deepest level of your 
    // categories 
    public Boolean HasChildren { 
     get { return _Item.Children != null; } 
    } 

    // Actual data item 
    public Object Item { 
     get { return _Item; } 
    } 

    // This is the path. 
    // Construct it as you think is necessary. 
    // Here the format is the same as in namespaces of C# 
    public String Path { 
     get { 
      var sb = new StringBuilder(); 
      var current = _Item; 
      sb.Append(_Item.CategoryName); 
      while (current != null) { 
       sb.Insert(0, "."); 
       sb.Insert(0, current.CategoryName); 
       current = current.Parent; 
      } 
      return sb.ToString(); 
     } 
    } 

    public String Type { 
     get { return "Category"; } 
    } 

    // returns the parent of the current item 
    public IHierarchyData GetParent() { 
     if (_Item.Parent != null) 
      return new CategoryHierarchyItem(_Item.Parent); 
     return null; 
    } 
} 

Я использовал вышеуказанные коды с фиктивными данными. Это выглядит примерно так.

protected void Page_Load(object sender, EventArgs e) { 

     // The topmost category 
     var top = new Category() { 
      CategoryId = 1, 
      CategoryName = "Top category" 
     }; 
     // Prepare children for them 
     var children = new List<Category>(); 
     // assign the children 
     top.Children = children; 
     // Populate the child list 
     children.Add(new Category { 
      CategoryId = 2, 
      CategoryName = "First child", 
      Parent = top 
     }); 
     children.Add(new Category { 
      CategoryId = 3, 
      CategoryName = "Second child", 
      Parent = top 
     }); 
     //Add another sub child 
     var thirdLevel = new List<Category>(); 
     thirdLevel.Add(new Category { 
      CategoryId = 4, 
      CategoryName = "Sub sub category", 
      Parent = children[0] 
     }); 
     // assign it to the first child 
     children[0].Children = thirdLevel; 
     // Make up a new tree 
     var tree = new CategoryTree(new[] { top }); 
     //Bind the source. 
     TreeView1.DataSource = tree; 
     // Bind it and enjoy. 
     TreeView1.DataBind(); 
    } 

Вы можете каким-либо образом модифицировать решение. Скорее всего, вам нужно разделить свою логику на доступ к данным и построение дерева пользовательского интерфейса.

+0

Что делать, если есть b категорий подкатегорий? Я не думаю, что это возможное решение, если я жестко задаю здесь названия категорий. что сказать? –

+0

Я хочу решение nth категорий, которое может быть изменено пользователем, когда он захочет .. –

+0

@AbidAli Не обращайте внимания. К моей «Жесткий код демо». Это просто пример. Ваш код реальной жизни должен заполнять список самых верхних категорий и рекурсивно детей. Глубина может быть такой, какой вы хотите. Это буквально «вечно». – Oybek

Смежные вопросы