首页 > 代码库 > C# Winfrom Treeview树形结构使用
C# Winfrom Treeview树形结构使用
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace TreeViewList
{
public partial class Form1 : Form
{
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string conString = "Data Source=服务器名称;Initial Catalog=数据库名;User ID=登陆名;Pwd=密码";
SqlConnection con = new SqlConnection(conString);
con.Open();
string strSql = "select * from 数据库表名";
SqlDataAdapter da = new SqlDataAdapter(strSql, con);
da.Fill(dt);
AddTreeNode(treeView1,0,null);
}
/// <summary>
/// 树形TreeView绑定数据
/// </summary>
/// <param name="tv"></param>
/// <param name="parentid"></param>
/// <param name="pNode"></param>
protected void AddTreeNode(TreeView tv,int parentid, TreeNode pNode)
{
foreach (DataRow dv in dt.Select("parentID="+parentid))
{
TreeNode node = new TreeNode();
node.Text = dv["Name"].ToString();
node.Tag = dv["ID"].ToString();
if (pNode == null)
{
tv.Nodes.Add(node);
}
else
{
pNode.Nodes.Add(node);
}
AddTreeNode(tv, Convert.ToInt32(dv["ID"].ToString()), node);
}
}
本文出自 “技术创造文明” 博客,请务必保留此出处http://smartboy.blog.51cto.com/3410319/1564871
C# Winfrom Treeview树形结构使用