2011/05/19(Thu) 12:06:30 編集(投稿者)
■No59208 (shu さん) に返信
> いまひとつどうなっているのか分かりませんがDictionary(of String,TreeNode)
> を使ってキーとTreeNodeの関連付けをされると良いかもしれません。
shuさんの案で実装してみました。
Dictionaryを使うことで、No59211 で書いた「行き来」の代わりができます。
ただし、ツリーに商品名は表示していませんので、商品名も表示しようとするともう一工夫必要になります。
// 前提:新規プロジェクトでを立ち上げ、treeView1とbutton1を配置。Form1_Loadイベント、button1_Clickイベントを準備。
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private DataTable dt;
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable("商品テーブル");
dt.Columns.Add("商品コード", typeof(string));
dt.Columns.Add("商品名", typeof(string));
dt.Columns.Add("使用商品", typeof(string));
dt.Rows.Add("111", "AAA", "222");
dt.Rows.Add("111", "AAA", "444");
dt.Rows.Add("111", "AAA", "555");
dt.Rows.Add("222", "BBB", "333");
dt.Rows.Add("333", "CCC", "");
dt.Rows.Add("444", "DDD", "333");
dt.Rows.Add("444", "DDD", "666");
dt.Rows.Add("555", "EEE", "");
dt.Rows.Add("666", "FFF", "");
}
private void button1_Click(object sender, EventArgs e)
{
Dictionary<string, TreeNode> nodes = new Dictionary<string, TreeNode>();
foreach (DataRow row in dt.Rows)
{
string parentKey = row.Field<string>("商品コード"); // (string)row["商品コード"] (.NET Framework3.5未満の場合)
string childKey = row.Field<string>("使用商品"); // (string)row["使用商品"] (.NET Framework3.5未満の場合)
TreeNode parent = null;
if (nodes.ContainsKey(parentKey))
{
parent = nodes[parentKey];
}
else
{
parent = new TreeNode(parentKey);
nodes.Add(parentKey, parent);
}
if (childKey != "")
{
TreeNode child = null;
if (nodes.ContainsKey(childKey))
{
// 注意:このフローは通らない
// ここに来るということは、複数の親が同一の子を持つということ
// それを許可する場合は、TreeViewでは表現できない
child = nodes[childKey];
}
else
{
child = new TreeNode(childKey);
nodes.Add(childKey, child);
parent.Nodes.Add(child);
}
}
}
foreach (TreeNode node in nodes.Values)
{
if (node.Parent == null)
{
treeView1.Nodes.Add(node);
}
}
treeView1.TopNode.Expand();
}
}
}