One of my friend want to convert Datatable to Tree Structure, hope this will help you.
class Program
{
static void Main(string[] args)
{
try
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", Type.GetType("System.Int32")));
dt.Columns.Add(new DataColumn("Name"));
dt.Columns.Add(new DataColumn("ParentNodeId", Type.GetType("System.Int32")));
DataRow dr = dt.NewRow();
dr[0] = "1";
dr[1] = "Number 1";
dr[2] = "0";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "2";
dr[1] = "Number 2";
dr[2] = "1";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "3";
dr[1] = "Number 3";
dr[2] = "2";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "4";
dr[1] = "Number 4";
dr[2] = "1";
dt.Rows.Add(dr);
new CreateTreeNode(dt, "Id", "Name", "ParentNodeId");
Console.WriteLine("Table Created...");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
Console.ReadKey();
}
}
public class TreeNode
{
public int Id { set; get; }
public string Name { get; set; }
public int ParentId { get; set; }
public List ChildeNodes { get; set; }
public TreeNode()
{
this.Id = this.ParentId = 0;
this.Name = string.Empty;
this.ChildeNodes = new List();
}
public TreeNode(int TreeNodeId, string TreeNodeName, int ParentNodeId)
: base()
{
this.Id = TreeNodeId;
this.Name = TreeNodeName;
this.ParentId = ParentNodeId;
}
}
public class CreateTreeNode
{
List _nodeList;
DataTable _dataTable;
string _nodeColumn;
string _displayNodeColumn;
string _parentNodeColumn;
CreateTreeNode()
{
this._nodeList = new List();
this._dataTable = new DataTable("TreeView");
}
public CreateTreeNode(DataTable dataTable, string NodeColumn, string DisplayNodeColumn, string ParentNodeColumn)
: base()
{
this._dataTable = dataTable;
this._nodeColumn = NodeColumn;
this._displayNodeColumn = DisplayNodeColumn;
this._parentNodeColumn = ParentNodeColumn;
this._nodeList = CreateTreeView(0);
int i = 0;
i++;
}
List CreateTreeView(int parentNodeId)
{
List nodeList;
DataRow[] SelectedRow = this._dataTable.Select(string.Format("{0}={1}", this._parentNodeColumn, parentNodeId));
TreeNode currentNode;
if (SelectedRow.Length <= 0)
return new List();
else
nodeList = new List();
foreach (DataRow currentRow in SelectedRow)
{
currentNode = new TreeNode();
currentNode.Id = Convert.ToInt32(currentRow[this._nodeColumn].ToString());
currentNode.Name = currentRow[this._displayNodeColumn].ToString();
currentNode.ParentId = Convert.ToInt32(currentRow[this._parentNodeColumn].ToString());
currentNode.ChildeNodes = CreateTreeView(currentNode.Id);
nodeList.Add(currentNode);
}
return nodeList;
}
}
No comments:
Post a Comment