I have a categories table which is set up to allow an infinite number of sub category levels. I would like to mimic the following:
It should be clarified that sub categories can have sub categories. E.g. Parent cat -> level 1 -> level 2 -> level 3 etc.
My categories table has two columns, CategoryName
and ParentID
.
This list box will be used when assigning the correct category to a product.
How can I write this?
Edit
In response to thedugas
I had to modify your answer to work with my situation. I found some errors that needed to be fixed, but below is a final, working solution.
protected void Page_Load(object sender, EventArgs e)
{
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
var c = db.Categories.Select(x => x);
List<Category> categories = new List<Category>();
foreach (var n in c)
{
categories.Add(new Category()
{
categoryID = n.categoryID,
title = n.title,
parentID = n.parentID,
isVisible = n.isVisible
});
}
List<string> xx = new List<string>();
foreach (Category cat in categories)
{
BuildCatString(string.Empty, cat, categories, xx);
}
ListBox1.DataSource = xx;
ListBox1.DataBind();
}
}
private void BuildCatString(string prefix, Category cat, IEnumerable<Category> categories, List<string> xx)
{
if (cat.parentID == 0)
{
xx.Add(cat.title);
prefix = cat.title;
}
var children = categories.Where(x => x.parentID == cat.categoryID);
if (children.Count() == 0)
{
return;
}
foreach (Category child in children)
{
if(prefix.Any())
{
xx.Add(prefix + "/" + child.title);
BuildCatString(prefix + "/" + child.title,
child, categories, xx);
}
}
}
Here is the almost finished work:
List<Category> categories
with the entire table, but I'm still getting the same results. When the code goes to evaulatevar children = categories.Where(cats => cats.parentID == cats.categoryID);
it finds none, which is strange because there is rows that have a parentID which matches parent rows ID. – Resistencia