TreeViewコントロールツリーDemoはDataTableでTreeViewにバインド
2246 ワード
フロント:
バックグラウンド:
バックグラウンド:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace TreeViewDemo
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
iniTree();
}
}
private DataTable CreateData()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("cName"));
dt.Columns.Add(new DataColumn("cID"));
dt.Columns.Add(new DataColumn("cPID"));
for (int i = 0; i < 10; i++)
{
DataRow dr = dt.NewRow();
dr["cName"] = " " + i.ToString();
dr["cID"] = i.ToString();
dr["cPID"] = "";
dt.Rows.Add(dr);
for (int j = 0; j < 3; j++)
{
DataRow dr_sub = dt.NewRow();
dr_sub["cName"] = " " + j.ToString();
dr_sub["cID"] = i.ToString() + "_" + j.ToString();
dr_sub["cPID"] = i.ToString();
dt.Rows.Add(dr_sub);
}
}
return dt;
}
private void iniTree()
{
TreeView1.Nodes.Clear();
DataTable dt = CreateData();
TreeView1.Nodes.Add(new TreeNode(" ", ""));
bindTree(dt, "", TreeView1.Nodes[0]);
TreeView1.ImageSet = TreeViewImageSet.Arrows;
}
private void bindTree(DataTable dt, string pid, TreeNode ParentNode)
{
DataRow[] Rows = GetData(dt, pid);
if (Rows.Length == 0) { return; }
foreach (DataRow r in Rows)
{
TreeNode node = new TreeNode(r["cName"].ToString(),r["cID"].ToString());
ParentNode.ChildNodes.Add(node);
bindTree(dt, r["cID"].ToString(), node);
}
}
private DataRow[] GetData(DataTable dt, string pid)
{
IEnumerable<DataRow> query = from r in dt.AsEnumerable()
where r.Field<string>("cPID") == pid
select r;
return query.ToArray<DataRow>();
}
}
}