Mohammad Olwan

Mohammad Olwan

  • NA
  • 14
  • 3.7k

how can i create treeview depending on datagridview

Oct 13 2015 1:06 PM

hello.

i get data from two database db1, db2, into one datagridview, this dtatgridview has three columns[Id, Name, DirectorId], only the first row has no director, and each director has one or more child, so that i want to create treeview that have one main node, and each node can has one or more of childNode, for that, i declare :

public struct person
{
public string name;
public string id;
public string father;
}

then convert datagridview into datatable:

public void ConverData()
{
DataTable dt = new DataTable();
foreach (DataGridViewColumn col in DataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText);
}

foreach (DataGridViewRow row in DataGridView1.Rows)
{
DataRow dRow = dt.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dRow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dRow);
}
}

after that i will get data from datagridview using LINQ, and convert these data to nodetree:

public void setTree()
{
var per = (from n in dt.AsEnumerable()
select new person()
{
name= n.Field<string>("Name"),
id = n.Field<string>("ID"),
father = n.Field<string>("Father")
}).ToList();

var rootTreeNode = GetTree(per, "0").First();------------------------------------------------------------------(1)
treeView1.Nodes.Add(rootTreeNode);

}
private TreeNode[] GetTree(List<person> per, string parent)
{
return per.Where(p => p.father == parent).Select(p =>
{
var node = new TreeNode(p.name);
node.Tag = p.id;
node.Nodes.AddRange(GetTree(per, p.id));
return node;
}).ToArray();
}

when i test it, i get error at mark(1) above, that say: Additional information: Sequence contains no elements.

now, where is the error for solve it?

thank you very much


Answers (2)