Nested loops on a self referencing table

  • Thread starter Thread starter Andrew Banks
  • Start date Start date
A

Andrew Banks

I have a database table with the following kind of structure

CategoryID (int)
Parent CategoryID (int)
CategoryName (varchar)

The table has a self referencing relationship between ParentCategoryID
CategoryID.

In C#.NET how can I loop through this table and list all categories,
with their sub-categories all the way down the hierarchy?

For example

Category 1
- Sub Category 1
--Sub Sub Category 1
--Sub Sub Category 2
--Sub Sub Category 3
Category 2
- Sub Category 1
--Sub Sub Category 1
- Sub Category 2
- Sub Category 3
--Sub Sub Category 1
--Sub Sub Category 2
--Sub Sub Category 3

I know I need to use a nested loop in some way but not sure how to take
this forward

Thanks in advance
 
Andrew,
Load the table into a dataTable and try something like this

ListItems(dataTable, 0);
..
..
..
..
public void ListItems(DataTable dataTable, int categoryID)
{
foreach (DataRow dataRow in dataTable.Rows)
{
if ((int)dataRow[ "Parent CategoryID" ] == categoryID)
{
ListItems(dataTable, (int)dataRow[ "CategoryID" ]);
}
}
}

All the Best,
Phil.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top