I am a danish programmer living in Bangkok.
Read more about me @ rasmus.rummel.dk.
Webmodelling Home > ASP.NET > C# Utility Functions > DataTable Get SubHierarchy

DataTable Get SubHierarchy

Usage

  • Example
    • In my Discussions WebControl I need to calculate how many discussions there are collectively under a category, which I do by using GetSubHierarchy to find the whole sub hierarchy of categories and count direct discussions under each category.
  • Example Code
    • DataTable myTable = GetData(); //your custom function
      DataTable dtSubHierarchy = Utils.DataTable.GetSubHierarchy(myTable, 8, "ID""PID""SortOrder");
      
      dtSubHierarchy now contains the sub hierarchy recursively ordered starting from node with ID=8.

The GetSubHierarchy function :

public static DataTable GetSubHierarchy(DataTable pdtSource, int pIDValue, string pIDColumn, string pPIDColumn, string pSortColumn)
{
	DataTable dtResult = pdtSource.Clone();
 
	pdtSource.PrimaryKey = new DataColumn[] { pdtSource.Columns[pIDColumn] };
 
	DataRow drCurrent = pdtSource.Rows.Find(pIDValue);
 
	if (drCurrent != null)
	{
		dtResult.Rows.Add(drCurrent.ItemArray);
 
		DataView dv = new DataView(pdtSource);
		dv.RowFilter = pPIDColumn + " = " + pIDValue;
		dv.Sort = pSortColumn;
 
		foreach (DataRowView drv in dv)
		{
			dtResult.Rows.Add(drv.Row.ItemArray);
 
			int currentID = (int)drv[pIDColumn];
			GetSubHierarchyHelper(pdtSource, ref dtResult, currentID, pIDColumn, pPIDColumn, pSortColumn);
		}
	}
 
	return dtResult;
}
private static void GetSubHierarchyHelper(DataTable pdtSource, ref DataTable pdtResult, int pIDValue, string pIDColumn, string pPIDColumn, string pSortColumn)
{
	DataView dv = new DataView(pdtSource);
	dv.RowFilter = pPIDColumn + " = " + pIDValue;
	dv.Sort = pSortColumn;
 
	foreach (DataRowView drv in dv)
	{
		pdtResult.Rows.Add(drv.Row.ItemArray);
 
		int currentID = (int)drv[pIDColumn];
		GetSubHierarchyHelper(pdtSource, ref pdtResult, currentID, pIDColumn, pPIDColumn, pSortColumn);
	}
}

Comments

You can comment without logging in
Profile
Username
Password
Password
Email
Nickpic
Get notified on reply to own posts  (only works if you specify an email address)
Get notified on receiving a PM  (only works if you specify an email address)
Remember my username
Remember my password
signature
Words: Chars: Chars left: