san
san

Reputation: 1

how to fill tree view by datagridview's data

i have a dataGridView with 3 columns (city ,subcity,citycode)and data in each one! i want to fill tree's parents by one of dataGridView column's values (city) and fill child of tree by "subCity" column's value please help me thanks

Upvotes: 0

Views: 1933

Answers (1)

MBulli
MBulli

Reputation: 1709

I assume its unkown which subcities belong to which city.

If you don't have any other data model, I would walk thru all rows of the datagrid and collect the data in a Dictionary>. The key would be the city and the value a collection of subcities. Now you can enumarete this dicionary and add foreach key a parent node and for every element of the value a child node.

This is a straightforward approach and I'm sure you can also do it with LINQ.

Edit:

treeView1.Nodes.Clear();

Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    string city = (string)row.Cells[0].Value;
    string subCity = (string)row.Cells[1].Value;

    if (city == null || subCity == null)
        continue;

    if (dict.ContainsKey(city))
    {
        dict[city].Add(subCity);
    }
    else
    {
        dict.Add(city, new List<string>());
        dict[city].Add(subCity);
    }
}

foreach (var kvp in dict)
{
    TreeNode parent = new TreeNode(kvp.Key);

    foreach (string subCity in kvp.Value)
    {
        parent.Nodes.Add(subCity);
    }

    treeView1.Nodes.Add(parent);
}

Upvotes: 1

Related Questions