PotatoBox
PotatoBox

Reputation: 608

Populate treeView from SQL Server Compact 3.5 database

I'm recently trying to populate treeView from database. I've got two columns and two rows. My goal is to make treeView look like this (Order is not important right now) :

My database looks like this:

enter image description here

I tried like this, but without luck

SqlCeCommand query = new SqlCeCommand("SELECT * FROM cars ORDER BY brand", con);
try
{
    SqlCeDataReader dr = query.ExecuteReader();

    while (dr.Read())
    {
        TreeNode node = new TreeNode(dr["model"].ToString());
        node.Nodes.Add(dr["brand"].ToString());

        treeView1.Nodes.Add(node);
    }
}
catch (Exception ex)
{
    MessageBox.Show("It's broken");
}

Upvotes: 1

Views: 282

Answers (1)

LarsTech
LarsTech

Reputation: 81620

Try finding the parent node (brand) by its key and if it's not there, you add it to the root node list:

while (dr.Read())
{
  TreeNode[] brandNode = treeView1.Nodes.Find(dr["brand"].ToString(), false);
  if (!brandNode.Any()) {
    brandNode = new TreeNode[] { treeView1.Nodes.Add(dr["brand"].ToString(),
                                                     dr["brand"].ToString()) };
  }
  brandNode[0].Nodes.Add(dr["model"].ToString(), dr["model"].ToString());
}

The sort order can be handled by your SQL: ORDER BY brand, model

Upvotes: 1

Related Questions