I am a danish programmer living in Bangkok.
Read more about me @ rasmus.rummel.dk.
Webmodelling Home > ASP.NET > C# Utility Functions > DropDownList - Indent Recursive

DropDownList Indent Recursive


  • Example
    • I use IndentRecursive at findthaifurniture.com search box to visually show that eg. "Dinner Tables" is a sub category of "Tables" - making it faster for the user to navigate the furniture categories in the search box.
  • Example Code
    • DataTable myTable = GetData(); //your custom function
      Utils.DataTable.OrderRecursive(ref myTable, "ID""PID""SortOrder"); //optional (adds a column called "RecursiveLevel" and orders your data recursively)
      DropDownList ddlCategories = Utils.DropDownList.IndentRecursive(myTable, "ID""Title""  - ");

The IndentRecursive function :

public static DropDownList IndentRecursive(DataTable pdtDataSource, string pDataValueField, string pDataTextField, string pIndention)
	DropDownList ddl = new DropDownList();
	foreach (DataRow dr in pdtDataSource.Rows)
		int dataValue = (int)dr[pDataValueField];
		string dataText = (string)dr[pDataTextField];
		int recursiveLevel = (int)dr["RecursiveLevel"]; //pdtDataSource MUST contain a column called "RecursiveLevel"
		string indent = "";
		for (var l = 0; l < recursiveLevel; l++)
			indent += pIndention;
		dataText = indent + dataText;
		string spaceDecode = System.Web.HttpContext.Current.Server.HtmlDecode("&nbsp;");
		dataText = dataText.Replace(" ", spaceDecode);
		ddl.Items.Add(new ListItem(dataText, dataValue.ToString()));
	return ddl;

Note that pDataSource MUST contain a column named "RecursiveLevel", however just run the pDataSource through the OrderRecursive function from the same library and pDataSource will be both correct ordered and contain the necessary column name for IndentRecursive.


You can comment without logging in
 B  U  I  S 
Words: Chars: Chars left: