如果需要给TreeNode绑定自己想要的属性解决办法?
自定义TreeNode 继承自.net的TreeNode后 添加属性如:
public class CustomTrNode : TreeNode
{
/// <summary>
/// 属性1:控件类型
/// </summary>
public object ControlType { get; set; }
/// <summary>
/// 属性2:父ID
/// </summary>
public object ParentID { get; set; }
}
在 NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)事件中如果 selectedNode==null的时候添加下面代码赋值
if (e.Button == MouseButtons.Left && CustomerTreeView.GetNodeAt(e.X, e.Y) != null)
{ CustomerTreeView.SelectedNode = CustomerTreeView.GetNodeAt(e.X, e.Y); }
CustomTrNode cuTrNode = (CustomTrNode)e.Node;
动态加载TreeView控件
TreeView tree = new TreeView();
private void Form1_Load(object sender, EventArgs e)
{
//读取数据库动态加载
String connStr = @"Data Source=localhost; Initial Catalog=TreeDB;uid=sa;pwd=123456";
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from TestInfo";
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
sda.Fill(ds, "TestInfo");
}
catch (Exception ex)
{
return;
}
DataTable dt = ds.Tables[0];
//初始化根节点
initParent(dt);
this.Controls.Add(tree);
tree.Width = 258;
tree.Height = 342;
tree.Left = 282;
tree.Top = 47;
}
//初始化根节点
void initParent(DataTable dt)
{
DataRow[] drs = dt.Select("ParentID=0");
foreach (DataRow dr in drs)
{
TreeNode tn = new TreeNode();
tn.Text = dr["Name"].ToString();
tn.Tag = dr["ID"].ToString();
this.tree.Nodes.Add(tn );
//初始化下级节点
initLeaf(dt,tn );
}
}
//初始化下级节点
void initLeaf(DataTable dt,TreeNode tn)
{
DataRow[] drs = dt.Select("ParentID="+tn.Tag as string );
foreach (DataRow dr in drs)
{
TreeNode ctn = new TreeNode();
ctn.Text = dr["Name"].ToString();
ctn.Tag = dr["ID"].ToString();
tn.Nodes.Add(ctn);
//递归调用,不断循环至叶节点
initLeaf(dt,ctn);
}
}
}