画面・グラフィック
- 階層構造を持つデータの内容をツリービューに表示
階層構造をもったデータをクラスで管理する場合、データクラスの中にツリーノードで出力するメソッドを用意しておくと 画面側で楽が出来ます。以下のように会社の部署、社員名簿を管理するようなクラスがあったとします。
using System.Drawing;
using System.Windows.Forms;
...
/// <summary>会社クラス</summary>
public class Kaisya
{
public string Name;
public List<Busyo> Busyos;
public Kaisya( string name )
{
Name = name;
Busyos = new List<Busyo>();
}
public TreeNode Node
{
get
{
TreeNode node = new TreeNode( Name );
node.ForeColor = Color.Blue;
node.ImageIndex = 0;
node.SelectedImageIndex = 0;
node.Tag = this;
foreach(Busyo item in Busyos )
{
node.Nodes.Add( item.Node );
}
return node;
}
}
}
/// <summary>部署クラス</summary>
public class Busyo
{
public string Name;
public List<Syain> Syains;
public Busyo( string name )
{
Name = name;
Syains = new List<Syain>();
}
public TreeNode Node
{
get
{
TreeNode node = new TreeNode( Name );
node.ForeColor = Color.Red;
node.ImageIndex = 1;
node.SelectedImageIndex = 1;
node.Tag = this;
foreach( Syain item in Syains )
{
node.Nodes.Add( item.Node );
}
return node;
}
}
}
/// <summary>社員クラス</summary>
public class Syain
{
public string Name;
public Syain( string name )
{
Name = name;
}
public TreeNode Node
{
get
{
TreeNode node = new TreeNode( Name );
node.ForeColor = Color.Black;
node.ImageIndex = 2;
node.SelectedImageIndex = 2;
node.Tag = this;
return node;
}
}
}
画面に表示する処理を書きます。
public partial class FormTree : Form
{
public FormTree()
{
InitializeComponent();
}
private void FormTree_Load( object sender, EventArgs e )
{
// ダミーデータ作成
Kaisya kaisya = new Kaisya( "豆エンヂニアリング" );
Busyo soumu = new Busyo( "総務部" );
kaisya.Busyos.Add( soumu );
soumu.Syains.Add( new Syain( "田中" ) );
soumu.Syains.Add( new Syain( "佐藤" ) );
soumu.Syains.Add( new Syain( "鈴木" ) );
Busyo koubai = new Busyo( "購買部" );
kaisya.Busyos.Add( koubai );
koubai.Syains.Add( new Syain( "吉田" ) );
koubai.Syains.Add( new Syain( "安部" ) );
koubai.Syains.Add( new Syain( "安田" ) );
Busyo eigyou = new Busyo( "営業部" );
kaisya.Busyos.Add( eigyou );
eigyou.Syains.Add( new Syain( "安藤" ) );
eigyou.Syains.Add( new Syain( "横田" ) );
Busyo gijyutu = new Busyo( "技術部" );
kaisya.Busyos.Add( gijyutu );
gijyutu.Syains.Add( new Syain( "加藤" ) );
gijyutu.Syains.Add( new Syain( "松本" ) );
gijyutu.Syains.Add( new Syain( "村田" ) );
// 画面に表示する処理はこれだけ
treeView1.ImageList = imageList1;
treeView1.Nodes.Add( kaisya.Node );
treeView1.ExpandAll();
treeView1.NodeMouseClick += new TreeNodeMouseClickEventHandler( treeView1_NodeMouseClick );
}
void treeView1_NodeMouseClick( object sender, TreeNodeMouseClickEventArgs e )
{
// ノードがクリックされた。
Kaisya kaisya = e.Node.Tag as Kaisya;
Busyo busyo = e.Node.Tag as Busyo;
Syain syain = e.Node.Tag as Syain;
}
}
結果表示