public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var treeView = new TreeView
{
Dock = DockStyle.Fill
};
this.Controls.Add(treeView);
var dt = GetDataTable();
PopulateTreeViewFromDataTable(treeView, dt);
}
private DataTable GetDataTable()
{
var dt = new DataTable("Цемент");
dt.Columns.AddRange(new[] {
new DataColumn("Name"),
new DataColumn("NameOfCement")
});
dt.Rows.Add("Портланд", "Вихрь");
dt.Rows.Add("Романцемент", "Тайга");
dt.Rows.Add("Романцемент", "Свой");
dt.Rows.Add("Алумацемент", "Курон");
return dt;
}
public void PopulateTreeViewFromDataTable(TreeView tv, DataTable dataTable)
{
var data =
dataTable
.AsEnumerable()
.Select(row => new
{
Name = row.Field<string>("Name"),
Cement = row.Field<string>("NameOfCement")
})
.GroupBy(x => x.Name);
tv.Nodes.Clear();
var root = tv.Nodes.Add(dataTable.TableName);
foreach (var gr in data)
{
var node = root.Nodes.Add(gr.Key);
foreach (var subItem in gr)
{
node.Nodes.Add(subItem.Cement);
}
}
}
}
foreach (DataRow v in table.Rows)
{
node.Nodes[0].Nodes.Add(v[0].ToString());
}
string x = " ";
for (int k = 0; k < node.Nodes[0.Nodes.Count; k++)
{
if (node.Nodes[0].Nodes[k].Text != x)
{
x = node.Nodes[0].Nodes[k].Text;
}
else
{
node.Nodes[0].Nodes.Remove(node.Nodes[0].Nodes[k]);
}
}
foreach (DataColumn col in table.Columns)
{
if (col.ColumnName == "Name")
{
foreach (DataRow row in table.Rows)
{
switch (row[col.ColumnName].ToString())
{
case "Портланд":
node.Nodes[0].Nodes[r].Nodes.Add(row[1].ToString());
r++;
break;
case "Романцемент":
node.Nodes[0].Nodes[r].Nodes.Add(row[1].ToString());
break;
case "Алумацемент":
r++;
node.Nodes[0].Nodes[r].Nodes.Add(row[1].ToString());
break;
}
}
}
}